/**
 * @filename OrderController.java
 */
package com.liupf.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.jfinal.aop.Before;
import com.jfinal.aop.ClearInterceptor;
import com.jfinal.aop.ClearLayer;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.util.PathUtil;
import com.liupf.OrderRunnable;
import com.liupf.common.utils.Constants;
import com.liupf.common.utils.LatLonDistance;
import com.liupf.common.utils.PushTokenUtils;
import com.liupf.common.utils.PushTokenUtils.JpushType;
import com.liupf.common.utils.SmsUtil;
import com.liupf.common.utils.TimeUtil;
import com.liupf.common.utils.TypeConstant;
import com.liupf.common.utils.TypeConstant.OrderType;
import com.liupf.domain.City;
import com.liupf.domain.DeliveryPrice;
import com.liupf.domain.Driver;
import com.liupf.domain.DriverPoint;
import com.liupf.domain.DriverPointRule;
import com.liupf.domain.Member;
import com.liupf.domain.Order;
import com.liupf.domain.OrderTrajectory;
import com.liupf.domain.Tel;
import com.liupf.domain.Terminal;
import com.liupf.domain.UserPoint;
import com.liupf.interceptor.ExceptionInterceptor;
import com.liupf.interceptor.SessionInViewInterceptor;

/**
 * @description 订单管理
 * @author shevliu
 * @email shevliu@gmail.com Jul 28, 2012 11:24:29 PM
 */
public class OrderController extends Controller {

	private static Log log = LogFactory.getLog(OrderController.class);

	//添加酒后代驾界面
	public void index() {
		String company=(String) getSession().getAttribute("company");
		Integer orderId = getParaToInt();
		if(orderId != null){
			Order order = Order.dao.findById(orderId);
			String cell_phone = order.getStr("cell_phone");
			String real_name = order.getStr("real_name");
			String startpoint = order.getStr("startpoint");
			setAttr("telCallNumb", cell_phone);
			setAttr("real_name", real_name);
			setAttr("startpoint", startpoint);
		}
		Date date=new Date();
		DateFormat formatDate=new SimpleDateFormat("yyyy-MM-dd");
		DateFormat formatTime=new SimpleDateFormat("HH:mm");
		
		DateFormat dayTime = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		String varDate=formatDate.format(date);
		String varTime=formatTime.format(date);
		
		DateFormat formatPointTime = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		String pointTime = formatPointTime.format(date);
		
		setAttr("varDate", varDate);
		setAttr("pointTime", pointTime);
		setAttr("varTime", varTime);
		setAttr("dayTime", dayTime);
		setAttr("orderCategoryType", TypeConstant.OrderType.DRIVER.name());
		
		List<Record> ruleList = Db.find("select * from tel_price_rule where company=?",company);
		setAttr("ruleList", ruleList);
		
		//常用地址选择
		int userid=(int) getSession().getAttribute("userId");
		List<UserPoint> points = UserPoint.dao.find("select * from user_point where userid=?",userid);
		setAttr("points", points);
		
		render("order_add3.ftl");
	}
	
	//同城配送添加订单界面
	public void deliveryAddOrder() {
		Date date=new Date();
		DateFormat formatDate=new SimpleDateFormat("yyyy-MM-dd");
		DateFormat formatTime=new SimpleDateFormat("HH:mm");
		DateFormat formatPointTime = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		
		String varDate = formatDate.format(date);
		String varTime = formatTime.format(date);
		String pointTime = formatPointTime.format(date);
		
		setAttr("varDate", varDate);
		setAttr("varTime", varTime);
		setAttr("pointTime", pointTime);
		
		List<City> citys = City.dao.find("select * from b_city");
		
		setAttr("citys", citys);
		
		setAttr("orderCategoryType", TypeConstant.OrderType.DELIVERY.name());
		
		String company=(String) getSession().getAttribute("company");
		List<Record> ruleList = Db.find("select * from tel_price_rule where company=?",company);
		setAttr("ruleList", ruleList);
		
		render("order_delivery_add3.ftl");
	}
	
	//车辆检修
	public void caroverhaulAddOrder() {
		Date date=new Date();
		DateFormat formatDate=new SimpleDateFormat("yyyy-MM-dd");
		DateFormat formatTime=new SimpleDateFormat("HH:mm");
		DateFormat formatPointTime = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		
		String varDate = formatDate.format(date);
		String varTime = formatTime.format(date);
		String pointTime = formatPointTime.format(date);
		
		setAttr("varDate", varDate);
		setAttr("varTime", varTime);
		setAttr("pointTime", pointTime);
		
		//setAttr("orderCategoryType", TypeConstant.OrderType.CAROVERHAUL.name());
		
		String company=(String) getSession().getAttribute("company");
		List<Record> ruleList = Db.find("select * from tel_price_rule where company=?",company);
		setAttr("ruleList", ruleList);
		
		render("order_caroverhaul_add3.ftl");
	}
	
	//车站订单
	public void stationAddOrder() {
		Date date=new Date();
		DateFormat formatDate=new SimpleDateFormat("yyyy-MM-dd");
		DateFormat formatTime=new SimpleDateFormat("HH:mm");
		DateFormat formatPointTime = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		
		String varDate = formatDate.format(date);
		String varTime = formatTime.format(date);
		String pointTime = formatPointTime.format(date);
		
		setAttr("varDate", varDate);
		setAttr("varTime", varTime);
		setAttr("pointTime", pointTime);
		
		//setAttr("orderCategoryType", TypeConstant.OrderType.STATION.name());
		
		String company=(String) getSession().getAttribute("company");
		List<Record> ruleList = Db.find("select * from tel_price_rule where company=?",company);
		setAttr("ruleList", ruleList);
		
		render("order_station_add3.ftl");
	}
		
	//机场订单
	public void airportAddOrder() {
		Date date=new Date();
		DateFormat formatDate=new SimpleDateFormat("yyyy-MM-dd");
		DateFormat formatTime=new SimpleDateFormat("HH:mm");
		DateFormat formatPointTime = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		
		String varDate = formatDate.format(date);
		String varTime = formatTime.format(date);
		String pointTime = formatPointTime.format(date);
		
		setAttr("varDate", varDate);
		setAttr("varTime", varTime);
		setAttr("pointTime", pointTime);
		
		//setAttr("orderCategoryType", TypeConstant.OrderType.AIRPORT.name());
		
		String company=(String) getSession().getAttribute("company");
		List<Record> ruleList = Db.find("select * from tel_price_rule where company=?",company);
		setAttr("ruleList", ruleList);
		
		render("order_airport_add3.ftl");
	}
	
	//开始服务
	public void unlockAddOrder() {
		Date date=new Date();
		DateFormat formatDate=new SimpleDateFormat("yyyy-MM-dd");
		DateFormat formatTime=new SimpleDateFormat("HH:mm");
		DateFormat formatPointTime = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		
		String varDate = formatDate.format(date);
		String varTime = formatTime.format(date);
		String pointTime = formatPointTime.format(date);
		
		setAttr("varDate", varDate);
		setAttr("varTime", varTime);
		setAttr("pointTime", pointTime);
		
		setAttr("orderCategoryType", TypeConstant.OrderType.UNLOCK.name());
		
		List<City> citys = City.dao.find("select * from b_city");
		setAttr("citys", citys);
		
		String company=(String) getSession().getAttribute("company");
		List<Record> ruleList = Db.find("select * from tel_price_rule where company=?",company);
		setAttr("ruleList", ruleList);
		
		render("order_unlock_add3.ftl");
	}
	
	//违章处理
	public void breakruleAddOrder(){
		Date date=new Date();
		DateFormat formatDate=new SimpleDateFormat("yyyy-MM-dd");
		DateFormat formatTime=new SimpleDateFormat("HH:mm");
		DateFormat formatPointTime = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		
		String varDate = formatDate.format(date);
		String varTime = formatTime.format(date);
		String pointTime = formatPointTime.format(date);
		
		setAttr("varDate", varDate);
		setAttr("varTime", varTime);
		setAttr("pointTime", pointTime);
		
		//setAttr("orderCategoryType", TypeConstant.OrderType.BREAKRULE.name());
		
		String company=(String) getSession().getAttribute("company");
		List<Record> ruleList = Db.find("select * from tel_price_rule where company=?",company);
		setAttr("ruleList", ruleList);
		
		render("order_breakrule_add3.ftl");
	}
	
	//违章处理
	public void cleanserverAddOrder(){
		Date date=new Date();
		DateFormat formatDate=new SimpleDateFormat("yyyy-MM-dd");
		DateFormat formatTime=new SimpleDateFormat("HH:mm");
		DateFormat formatPointTime = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		
		String varDate = formatDate.format(date);
		String varTime = formatTime.format(date);
		String pointTime = formatPointTime.format(date);
		
		setAttr("varDate", varDate);
		setAttr("varTime", varTime);
		setAttr("pointTime", pointTime);
		setAttr("wish_finish_time", pointTime);
		
		//setAttr("orderCategoryType", TypeConstant.OrderType.CLEANSERVER.name());
		
		String company=(String) getSession().getAttribute("company");
		List<Record> ruleList = Db.find("select * from tel_price_rule where company=?",company);
		setAttr("ruleList", ruleList);
		
		render("order_cleanserver_add3.ftl");
	}
	
	//违章处理
	public void trunkAddOrder(){
		Date date=new Date();
		DateFormat formatDate=new SimpleDateFormat("yyyy-MM-dd");
		DateFormat formatTime=new SimpleDateFormat("HH:mm");
		DateFormat formatPointTime = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		
		String varDate = formatDate.format(date);
		String varTime = formatTime.format(date);
		String pointTime = formatPointTime.format(date);
		
		setAttr("varDate", varDate);
		setAttr("varTime", varTime);
		setAttr("pointTime", pointTime);
		setAttr("wish_finish_time", pointTime);
		
		//setAttr("orderCategoryType", TypeConstant.OrderType.TRUNK.name());
		
		setAttr("trunkTypeArray", TypeConstant.trunkTypeArray);
		setAttr("goodsTypeArray", TypeConstant.goodsTypeArray);
		setAttr("goodsOrderTypeArray", TypeConstant.goodsOrderTypeArray);
		
		String company=(String) getSession().getAttribute("company");
		List<Record> ruleList = Db.find("select * from tel_price_rule where company=?",company);
		setAttr("ruleList", ruleList);
		
		render("order_trunk_add3.ftl");
	}
	
	//猎头招聘
	public void headhuntingAddOrder(){
		Date date=new Date();
		DateFormat formatDate=new SimpleDateFormat("yyyy-MM-dd");
		DateFormat formatTime=new SimpleDateFormat("HH:mm");
		DateFormat formatPointTime = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		
		String varDate = formatDate.format(date);
		String varTime = formatTime.format(date);
		String pointTime = formatPointTime.format(date);
		
		setAttr("varDate", varDate);
		setAttr("varTime", varTime);
		setAttr("pointTime", pointTime);
		
		//setAttr("orderCategoryType", TypeConstant.OrderType.HEADHUNTING.name());
		setAttr("educationTypeArray", TypeConstant.educationTypeArray);
		setAttr("positionTypeArray", TypeConstant.positionTypeArray);
		setAttr("jobStatusTypeArray", TypeConstant.jobStatusTypeArray);
		
		String company=(String) getSession().getAttribute("company");
		List<Record> ruleList = Db.find("select * from tel_price_rule where company=?",company);
		setAttr("ruleList", ruleList);
		
		render("order_headhunting_add3.ftl");
	}
	
	//猎头招聘
	public void babysitterAddOrder(){
		Date date=new Date();
		DateFormat formatDate=new SimpleDateFormat("yyyy-MM-dd");
		DateFormat formatTime=new SimpleDateFormat("HH:mm");
		DateFormat formatPointTime = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		
		String varDate = formatDate.format(date);
		String varTime = formatTime.format(date);
		String pointTime = formatPointTime.format(date);
		
		setAttr("varDate", varDate);
		setAttr("varTime", varTime);
		setAttr("pointTime", pointTime);
		setAttr("wish_finish_time", pointTime);
		
		//setAttr("orderCategoryType", TypeConstant.OrderType.BABYSITTER.name());
		
		String company=(String) getSession().getAttribute("company");
		List<Record> ruleList = Db.find("select * from tel_price_rule where company=?",company);
		setAttr("ruleList", ruleList);
		
		render("order_babysitter_add3.ftl");
	}
		
	public void add() {
		Member member = null;
		int memberId = getParaToInt();
		if (memberId == 0) {
			member = getModel(Member.class);
		} else {
			member = Member.dao.findById(memberId);
		}
		
		Date date=new Date();
		DateFormat formatDate=new SimpleDateFormat("yyyy-MM-dd");
		DateFormat formatTime=new SimpleDateFormat("HH:mm");
		String varDate=formatDate.format(date);
		String varTime=formatTime.format(date);
		
		setAttr("varDate", varDate);
		setAttr("varTime", varTime);
		
		setAttr("member", member);
		render("order_add3.ftl");

	}

	public void save() {
		Integer  orderId;
		
		int orderNum = this.getParaToInt("orderNum");
		String province = this.getPara("province");
		String city = this.getPara("city");
		
		Order order = getModel(Order.class);
		order.put("sys_user_id", getSession().getAttribute("userId"));
		order.put("create_time", new Date());
		order.put("order_state", 0);
		order.put("endpoint", province+city);
		order.put("order_state", 6);
		
		for (int i=0; i<orderNum; i++) {
			order.remove("id");
			order.save();
		}
		redirect("/order/assignmentList");
	}

	public void toApproval() {
		int orderId = getParaToInt();
		String sql = "select a.*,b.real_name ,b.user_name,b.cell_phone,b.sex ,b.plage_number from order_detail a left join driver_member b on a.member_id = b.id where a.id = ?";
		setAttr("order", Db.findFirst(sql, orderId));
		render("order_approval.ftl");
	}

	/**
	 * 临时订单审核
	 * 
	 * @description
	 * @author shevliu
	 * @email shevliu@gmail.com Aug 14, 2012 10:54:15 PM
	 */
	@Before(Tx.class)
	public void approval() {
		// Date now = new Date();
		Order order = getModel(Order.class);
		order.set("order_state", 14);
		// order.set("publish_time", new Date());
		order.update();
		// int orderId = order.getInt("id");
		// String tempDriver = order.getStr("temp_driver");
		// String sql = "insert into order_job(order_id , b_user_id , job_time
		// ,status) values ( ? , ? , ? , ?)";
		// if (StringUtils.isNotBlank(tempDriver)) {
		// String[] drivers = tempDriver.split("#");
		// for (String driverIdStr : drivers) {
		// int driverId = Integer.parseInt(driverIdStr);
		// Db.update(sql, orderId, driverId, now, 0);
		// }
		// } else {
		// throw new RuntimeException("该临时订单未选择代驾员，无法派单");
		// }
		redirect("/order/tempList");
	}

	/**
	 * 
	 * @description 根据历史订单生成新订单 ，转向
	 * @author shevliu
	 * @email shevliu@gmail.com Aug 19, 2012 4:23:56 PM
	 */
	public void addByHistory() {
		int orderId = getParaToInt();
		String sql = "select a.*,b.real_name ,b.user_name,b.cell_phone,b.sex ,b.plage_number from order_detail a left join driver_member b on a.member_id = b.id where a.id = ?";
		setAttr("order", Db.findFirst(sql, orderId));
		render("order_add_by_history.ftl");
	}

	/**
	 * 
	 * @description 根据历史订单生成新订单
	 * @author shevliu
	 * @email shevliu@gmail.com Aug 19, 2012 5:05:40 PM
	 */
	public void addByHistoryDo() {
		// Date now = new Date();
		// Order order = getModel(Order.class);
		// order.set("order_state", 14);
		// order.update();
		// redirect("/order/assignmentList");
	}
	
	public void queryAcceptOrderCount(){
		String userRole = (String) getSession().getAttribute("userRole");
		String company=(String) getSession().getAttribute("company");
		//String loadTime = getAttr("loadTime");
		String assignmentSql = "select count(*) from order_detail a where a.order_state=6 and (auto_status IN (0,2,3) OR (auto_status=1 AND create_time< ?))";
		String acceptSql = "select count(*) from order_detail a where a.order_state=0 ";
		
		if(Constants.ROLE_BRAND_MANAGER.equals(userRole) || Constants.ROLE_MIDDLE_MANAGER.equals(userRole)){
			assignmentSql +=" and a.source='"+company+"' ";
			acceptSql +=" and a.source='"+company+"' ";
		}
		
		Calendar nowDay = Calendar.getInstance();
		nowDay.add(Calendar.MINUTE, -1);
		Date date = nowDay.getTime();
		//Long assignmentCount = Db.queryLong(assignmentSql, date, loadTime);
		//Long acceptCount = Db.queryLong(acceptSql, loadTime);
		Long assignmentCount = Db.queryLong(assignmentSql, date);
		Long acceptCount = Db.queryLong(acceptSql);
		
		try {
			PrintWriter pw = getResponse().getWriter();
			pw.print(assignmentCount+","+acceptCount);
		} catch (IOException e) {
			e.printStackTrace();
		}
		renderNull();
	}

	/**
	 * 
	 * @description 待分派订单
	 * @author shevliu
	 * @email shevliu@gmail.com Jul 29, 2012 3:44:05 PM
	 */
	public void assignmentList() {
		//操作员自己所属品牌
		String company=(String) getSession().getAttribute("company");
		String userRole = (String)getSession().getAttribute("userRole");
		int purview=(Integer) getSession().getAttribute("purview");
		
	
		String id = getPara("id");
		/*String from = "from order_detail a left join driver_member b on a.member_id = b.id " +
				" left join b_user bu on a.b_user_id=bu.id " +
				" where a.order_state=6 ";*/
		Calendar nowDay = Calendar.getInstance();
		nowDay.add(Calendar.MINUTE, -1);
		Date date = nowDay.getTime();
		String from = "from order_detail a where a.order_state=6 and (auto_status IN (0,2,3) OR (auto_status=1 AND create_time< ?))";
		if (StringUtils.isNotBlank(id)) {
			from += " and a.id = " + id;
		}
		
		from = Constants.appendSqlForRoleCom(from,userRole,company);
		
		from += " order by a.id desc";
		Page<Record> page = Db
				.paginate(
						getParaToInt(0, 1),
						10,
						//"select a.*,b.real_name as real_name2,b.user_name,b.cell_phone as cell_phone2,b.sex as sex2 ,b.plage_number as plage_number2,bu.job_number as job_number",
						"select a.*",
						from,date);
		log.debug("list:" + page.getList());
		setAttr("page", page);
		render("assignment_list.ftl");
	}

    /**
     *
     * @description 待分派订单
     * @author shevliu
     * @email shevliu@gmail.com Jul 29, 2012 3:44:05 PM
     */
    public void assignmentAjaxList() {
        //操作员自己所属品牌
        String company=(String) getSession().getAttribute("company");
        String userRole = (String)getSession().getAttribute("userRole");
        String pageno=(String)getRequest().getParameter("page");
        int purview=(Integer) getSession().getAttribute("purview");

        if(pageno==null||"".equals(pageno))
            pageno="0";

        String id = getPara("id");
		/*String from = "from order_detail a left join driver_member b on a.member_id = b.id " +
				" left join b_user bu on a.b_user_id=bu.id " +
				" where a.order_state=6 ";*/
        Calendar nowDay = Calendar.getInstance();
        nowDay.add(Calendar.MINUTE, -1);
        Date date = nowDay.getTime();
        String from = "from order_detail a where a.order_state=6 and (auto_status IN (0,2,3) OR (auto_status=1 AND create_time< ?))";
        if (StringUtils.isNotBlank(id)) {
            from += " and a.id = " + id;
        }

        from = Constants.appendSqlForRoleCom(from,userRole,company);

        from += " order by a.id desc";
        Page<Record> page = Db
                .paginate(
                        Integer.parseInt(pageno),
                        10,
                        //"select a.*,b.real_name as real_name2,b.user_name,b.cell_phone as cell_phone2,b.sex as sex2 ,b.plage_number as plage_number2,bu.job_number as job_number",
                        "select a.*",
                        from,date);
        Long totalCount=Db.findFirst("select count(1) num "+from,date).getLong("num");
        Long pageCount=0l;
        if(totalCount%10>0){
            pageCount=totalCount/10+1;
        }else
            pageCount=totalCount/10;
        setAttr("pageCount", pageCount);
        setAttr("totalCount", totalCount);
        log.debug("list:" + page.getList());
        setAttr("page", page);


        render("assignmentAJAX_list.ftl");
    }

	/**
	 * 
	 * @description 待接受订单
	 * @author shevliu
	 * @email shevliu@gmail.com Jul 29, 2012 3:44:05 PM
	 */
	public void acceptList() {
		//操作员自己所属品牌
		String company=(String) getSession().getAttribute("company");
        String contentType=(String)getRequest().getParameter("contentType");
		//int purview=(Integer) getSession().getAttribute("purview");
        int pageno=getParaToInt(0, 1);
        if("ajaxHtml".equals(contentType)){
            String pagenum=getRequest().getParameter("page");
            if(pagenum==null||pagenum.equals("")){
                pageno=0;
            }else
                pageno=Integer.parseInt(pagenum);
        }

		String userRole = (String) getSession().getAttribute("userRole");
		String id = getPara("id");
		String from = "from order_detail a left join driver_member b on a.member_id = b.id " +
				" left join b_user bu on a.b_user_id=bu.id " +
				" where a.order_state=0 ";
		
		if (StringUtils.isNotBlank(id)) {
			from += " and a.id = " + id;
		}
		from = Constants.appendSqlForRoleCom(from, userRole, company);
		
		//from += " and a.source='"+company+"' ";
		//from = Constants.appendSqlForRole(from, userRole, company);
		
		from += " order by a.id desc";
		Page<Record> page = Db
				.paginate(
                        pageno,
						10,
						"select a.*,TIMESTAMPDIFF(MINUTE ,a.publish_time,now()) as timeDiffe,b.real_name as real_name2,b.user_name,b.cell_phone as cell_phone2,b.sex as sex2 ,b.plage_number as plage_number2, " +
								" (select count(*) from order_job where order_id = a.id ) driverCount ," +
								" (select name from order_job j left join b_user b on b.id=j.b_user_id where j.order_id = a.id limit 1) driverName ," +
								" (select job_number from order_job j left join b_user b on b.id=j.b_user_id where j.order_id = a.id limit 1) jobNumber ," +
								" bu.job_number as job_number,a.order_category_type",
						from);
		setAttr("page", page);

        if(!"ajaxHtml".equals(contentType)) {
            render("accept_list.ftl");
        }else{
            Long totalCount=Db.findFirst("select count(1) num "+from).getLong("num");
            Long pageCount=0l;
            if(totalCount%10>0){
                pageCount=totalCount/10+1;
            }else
                pageCount=totalCount/10;
            setAttr("pageCount", pageCount);
            setAttr("totalCount", totalCount);
            render("acceptAJAX_list.ftl");
        }
	}

	/**
	 * 已接受订单
	 */
	public void acceptedList() {
		//操作员自己所属品牌
		String company=(String) getSession().getAttribute("company");
		//int purview=(Integer) getSession().getAttribute("purview");
		String userRole = (String) getSession().getAttribute(Constants.SESSION_USER_ROLE);
		String job_number = getPara("job_number");
		String real_name = getPara("real_name");
		String cell_phone = getPara("cell_phone");

        String contentType=(String)getRequest().getParameter("contentType");
        //int purview=(Integer) getSession().getAttribute("purview");
        int pageno=getParaToInt(0, 1);
        if("ajaxHtml".equals(contentType)){
            String pagenum=getRequest().getParameter("page");
            if(pagenum==null||pagenum.equals("")){
                pageno=0;
            }else
                pageno=Integer.parseInt(pagenum);
        }

		String id = getPara("id");
		String from = "from order_detail a left join driver_member b on a.member_id = b.id left join b_user bu on a.b_user_id = bu.id  where a.order_state=1 ";
		
		//String from = "from order_detail a where a.order_state=1";
		if (StringUtils.isNotBlank(id)) {
			from += " and a.id = " + id;
		}
		if(StringUtils.isNotBlank(job_number)){
			from += " and bu.job_number = '" + job_number +"'";
		}
		if(StringUtils.isNotBlank(real_name)){
			from += " and a.real_name = '" + real_name +"'";
		}
		if(StringUtils.isNotBlank(cell_phone)){
			from += " and a.cell_phone = '" + cell_phone +"'";
		}
		
		from = Constants.appendSqlForRoleCom(from, userRole, company);
		
		from += " order by a.id desc";
		Page<Record> page = Db
				.paginate(
						pageno,
						10,
						"select a.*,b.real_name as real_name2,b.user_name,b.cell_phone as cell_phone2,b.sex as sex2 ,b.plage_number as plage_number2,bu.name as driver_name , bu.job_number,bu.phone as driver_phone,a.order_category_type ",
						from);
		setAttr("page", page);
        if(!"ajaxHtml".equals(contentType)) {
            render("accepted_list.ftl");
        }else{
            Long totalCount=Db.findFirst("select count(1) num "+from).getLong("num");
            Long pageCount=0l;
            if(totalCount%10>0){
                pageCount=totalCount/10+1;
            }else
                pageCount=totalCount/10;
            setAttr("pageCount", pageCount);
            setAttr("totalCount", totalCount);
            render("acceptedAJAX_list.ftl");
        }
	}

	/**
	 * 已到达订单
	 */
	public void arrivedList() {
		//操作员自己所属品牌
		String company=(String) getSession().getAttribute("company");
		//int purview=(Integer) getSession().getAttribute("purview");
		String userRole = (String)getSession().getAttribute("userRole");
		System.out.println("*************userRole:"+userRole);
		System.out.println("*************company:"+company);

        String contentType=(String)getRequest().getParameter("contentType");
        int pageno=getParaToInt(0, 1);
        if("ajaxHtml".equals(contentType)){
            String pagenum=getRequest().getParameter("page");
            if(pagenum==null||pagenum.equals("")){
                pageno=0;
            }else
                pageno=Integer.parseInt(pagenum);
        }

		String job_number = getPara("job_number");
		String real_name = getPara("real_name");
		String cell_phone = getPara("cell_phone");
		
		String id = getPara("id");
		String from = "from order_detail a left join driver_member b on a.member_id = b.id left join b_user bu on a.b_user_id = bu.id  where a.order_state=2 ";
		
		//String from = "from order_detail a where a.order_state=2";
		
		if (StringUtils.isNotBlank(id)) {
			from += " and a.id = " + id;
		}
		if(StringUtils.isNotBlank(job_number)){
			from += " and bu.job_number = '" + job_number +"'";
		}
		if(StringUtils.isNotBlank(real_name)){
			from += " and a.real_name = '" + real_name +"'";
		}
		if(StringUtils.isNotBlank(cell_phone)){
			from += " and a.cell_phone = '" + cell_phone +"'";
		}
		from = Constants.appendSqlForRoleCom(from, userRole, company);
		
		from += " order by a.id desc";
		Page<Record> page = Db
				.paginate(
						pageno,
						10,
						"select a.*,b.real_name as real_name2,b.user_name,b.cell_phone as cell_phone2,b.sex as sex2 ,b.plage_number as plage_number2,bu.name as driver_name,bu.job_number,bu.phone as driver_phone,a.order_category_type ",
						from);
		setAttr("page", page);
        if(!"ajaxHtml".equals(contentType)) {
            render("arrived_list.ftl");
        }else{
            Long totalCount=Db.findFirst("select count(1) num "+from).getLong("num");
            Long pageCount=0l;
            if(totalCount%10>0){
                pageCount=totalCount/10+1;
            }else
                pageCount=totalCount/10;
            setAttr("pageCount", pageCount);
            setAttr("totalCount", totalCount);
            render("arrivedAJAX_list.ftl");
        }
	}

	/**
	 * 
	 * @description 客户取消订单
	 * @author shevliu
	 * @email shevliu@gmail.com Jul 29, 2012 4:40:42 PM
	 */
	@Before(Tx.class)
	public void cancel() {
		int orderId = getParaToInt("id");
		int isAccept = getParaToInt("isAccept");
		String cancel = getPara("cancel");

		if (isAccept == 0) {// 未接取消
			Db.update(
					"update order_detail set order_state = 8 , cancel=?  where id = ?",
					cancel, orderId);
			redirect("/order/noApprovalList");
		} else { // 已接取消
			Db.update(
					"update order_detail set order_state = 9 , cancel=?  where id = ?",
					cancel, orderId);
			// 修改司机状态为空闲
			Db.update(
					"update b_user set status = 0 where id = (select b_user_id from order_detail where id = ?)",
					orderId);
			redirect("/order/noApprovalList");
		}
		
		Order order = Order.dao.findById(orderId);
		
		DriverPoint driverPoint = (DriverPoint)getModel(DriverPoint.class);
		driverPoint.put("point", -3);
		driverPoint.put("user_id", order.get("b_user_id"));
		driverPoint.put("order_id", orderId);
		driverPoint.put("create_time", new Date());
		driverPoint.put("remarks", "取消订单");
		driverPoint.save();
		
		Integer memberId = order.getInt("member_id");
		
		Db.update("update b_user set point=point-3 where id = ?",
				   order.get("b_user_id"));
		
		if(!(memberId == null || memberId == 0)){
			String sql2 = "SELECT * FROM driver_member WHERE id = ?";
			Record record2 = Db.findFirst(sql2, memberId);
			String tel = "";
			
			String content = "订单：" + orderId + "取消，取原因：" + cancel;
			if(record2 != null){
				String phoneType = record2.getStr("phone_type");
				String registerId = record2.getStr("device_id");
				
				if("IOS".equals(phoneType)){
					SmsUtil.sendPush(content, null, registerId, phoneType);
				}else if("ANDROID".equals(phoneType)){
					SmsUtil.sendPush("成功接单", content, registerId, phoneType);
				}else{
					Order order1 = Order.dao.findById(orderId);
					String company = order1.getStr("source");
					SmsUtil.sendMessage(tel,content,company);
					
					//String insertMessage = "insert into tel_company_message(TEL,MESSAGE,COMPANY,CREATE_TIME) values(?,?,?,?)";
					//Db.update(insertMessage,tel,content,TypeConstant.admin,new java.sql.Date(Calendar.getInstance().getTime().getTime()));
				}
			}
		}
		
		//给司机发送短信
		/*if (isAccept != 0 ) {
			File configFile = new File(PathUtil.getWebRootPath(),
					"/WEB-INF/config.properties");
			SmsUtil.init(configFile);
			
			Connection conn = SmsUtil.getConn();
			PreparedStatement ps = null;
			String sql = "select b.*,t.* from b_user b , order_detail t where t.id = '"+orderId+"' and t.b_user_id = b.id; ";
			try {
				ps = conn.prepareStatement(sql);
				ResultSet rs = ps.executeQuery();
				if(rs.next()) {
					String  phone = rs.getString("phone");
					String content = "订单：" + orderId + "取消，取原因：" + cancel;
					SmsUtil.sendMessage(phone, content);
				}
			} catch (SQLException e) {
				log.info("cancel failure,error:"+e.getMessage());
				e.printStackTrace();
			}
		}*/
	}

	/**
	 * 未接取消
	 */
	public void cancelNotAccept() {
		int orderId = getParaToInt();
		setAttr("id", orderId);
		setAttr("isAccept", 0);
		render("cancel_order.ftl");
	}

	/**
	 * 已接取消
	 */
	public void cancelAccepted() {
		int orderId = getParaToInt();
		setAttr("id", orderId);
		setAttr("isAccept", 1);
		render("cancel_order.ftl");
	}

	/**
	 * 代驾员撤销订单，转向
	 */
	public void driverCancel() {
		int orderId = getParaToInt();
		setAttr("id", orderId);
		render("driver_cancel_order.ftl");
	}

	/**
	 * 代驾员撤销订单
	 */
	@Before(Tx.class)
	public void driverCancelDo() {
		int orderId = getParaToInt("id");
		String cancel = getPara("cancel");
		Db.update(
				"update order_detail set order_state = 12 , cancel_driver=?  where id = ?",
				cancel, orderId);
		// 修改司机状态为空闲
		Db.update(
				"update b_user set status = 0 where id = (select b_user_id from order_detail where id = ?)",
				orderId);
		redirect("/order/driverCancelList");
	}

	/**
	 * 代驾员撤销订单，审核转向
	 */
	public void driverCancelApproval() {
		int orderId = getParaToInt();
		setAttr("id", orderId);
		render("accepted_approval.ftl");
	}

	/**
	 * 代驾员撤销订单，审核
	 */
	@Before(Tx.class)
	public void driverCancelApprovalDo() {
		int orderId = getParaToInt("id");
		String content = getPara("content");
		int refund = getParaToInt("refund");
		log.debug("refund:" + refund);
		int userId = NumberUtils
				.toInt(getSession().getAttribute("userId") + "");
		log.debug("userId:" + userId);
		Db.update(
				"update order_detail set order_state = 13 , cancel_approval_opinion=? ,cancel_audit=? ,refund = ? where id = ?",
				content, userId, refund, orderId);
		// 如果需要退款，则将账户余额加上
		if (refund == 1) {
			Record record = Db
					.findFirst(
							"select a.totalmoney,a.charges,b.proportion,a.b_user_id  from order_detail a left join b_user b on a.b_user_id = b.id where a.id=? limit 1",
							orderId);
			log.debug("record:" + record);
			BigDecimal totalmoney = record.getBigDecimal("totalmoney");
			log.debug("totalmoney" + totalmoney.toString());
			BigDecimal charges = record.getBigDecimal("charges");
			log.debug("charges" + charges.toString());
			BigDecimal refundMoney = totalmoney.subtract(charges);
			log.debug("refundMoney:" + refundMoney.toString());

			Db.update("update b_user set  balance = balance+? where id = ?",
					refundMoney, record.getInt("b_user_id"));

		}
		redirect("/order/driverCancelList");
	}

	/**
	 * 订单投诉，转向
	 */
	public void complaint() {
		int orderId = getParaToInt();
		setAttr("id", orderId);
		render("complaint.ftl");
	}

	/**
	 * 订单投诉
	 */
	@Before(Tx.class)
	public void doComplaint() {
		int orderId = getParaToInt("id");
		String complaint_content = getPara("complaint_content");
		Db.update(
				"update order_detail set ishave_complaint = 1 , complaint_content=?  where id = ?",
				complaint_content, orderId);
		
		Order order = Order.dao.findById(orderId);
		
		DriverPoint driverPoint = (DriverPoint)getModel(DriverPoint.class);
		driverPoint.put("point", -3);
		driverPoint.put("user_id", order.get("b_user_id"));
		driverPoint.put("order_id", orderId);
		driverPoint.put("create_time", new Date());
		driverPoint.put("remarks", "投诉");
		driverPoint.save();
		
		Db.update("update b_user set point=point-3 where id = ?",
				   order.get("b_user_id"));
		
		redirect("/order/complaintList");
	}

	/**
	 * 订单投诉处理，转向
	 */
	public void complaintApproval() {
		int orderId = getParaToInt();
		setAttr("id", orderId);
		render("complaint_approval.ftl");
	}

	/**
	 * 订单投诉处理
	 */
	public void doComplaintApproval() {
		int orderId = getParaToInt("id");
		String content = getPara("content");
		int userId = NumberUtils
				.toInt(getSession().getAttribute("userId") + "");
		Db.update(
				"update order_detail set ishave_complaint = 2 , complaint_approval_opinion=? ,complaintl_audit=? where id = ?",
				content, userId, orderId);
		redirect("/order/complaintList");
	}

	/**
	 * 未接取消订单 审核，转向
	 */
	public void cancelNotAcceptApproval() {
		int orderId = getParaToInt();
		setAttr("id", orderId);
		render("cancel_not_accept_approval.ftl");
	}

	/**
	 * 已接取消订单 审核，转向
	 */
	public void cancelAcceptedApproval() {
		int orderId = getParaToInt();
		setAttr("id", orderId);
		render("accepted_approval.ftl");
	}

	/**
	 * 审核订单
	 */
	public void acceptedApproval() {
		int orderId = getParaToInt();
		setAttr("id", orderId);
		setAttr("order", Order.dao.findById(orderId));
		render("accepted_approval.ftl");
	}

	public void doAcceptedApproval() throws Exception {

		int orderId = getParaToInt("id");
		String content = getPara("content");
		int refund = getParaToInt("refund");
		log.debug("refund:" + refund);
		int userId = NumberUtils
				.toInt(getSession().getAttribute("userId") + "");
		log.debug("userId:" + userId);

		Order order = Order.dao.findById(orderId);
		if (order == null) {
			throw new Exception("订单不存在");
		}
		int orderState = ((Long) order.get("order_state")).intValue();
		if (orderState != 8 && orderState != 9 && orderState != 12) {
			throw new Exception("订单不是待审核状态");
		}
		if (orderState == 8) {
			Db.update(
					"update order_detail set order_state = 10 , cancel_approval_opinion=? ,cancel_audit=? where id = ?",
					content, userId, orderId);

		} else if (orderState == 9) {
			Db.update(
					"update order_detail set order_state = 11 , cancel_approval_opinion=? ,cancel_audit=? ,refund = ? where id = ?",
					content, userId, refund, orderId);
			// 如果需要退款，则将账户余额加上
			if (refund == 1) {
				Record record = Db
						.findFirst(
								"select a.totalmoney,b.proportion,a.b_user_id  from order_detail a left join b_user b on a.b_user_id = b.id where a.id=? limit 1",
								orderId);
				log.debug("record:" + record);
				BigDecimal totalmoney = record.getBigDecimal("totalmoney");
				log.debug("totalmoney" + totalmoney);
				int proportion = record.getInt("proportion");
				log.debug("proportion" + proportion);
				BigDecimal refundMoney = totalmoney.multiply(
						new BigDecimal(proportion)).divide(new BigDecimal(100));
				log.debug("refundMoney:" + refundMoney.toString());
				BigDecimal inCome = totalmoney.subtract(refundMoney);

				Db.update(
						"update b_user set  balance = balance+?,income = income-? where id = ?",
						refundMoney, inCome, record.getInt("b_user_id"));

			}

		} else {
			Db.update(
					"update order_detail set order_state = 13 , cancel_approval_opinion=? ,cancel_audit=? ,refund = ? where id = ?",
					content, userId, refund, orderId);
			// 如果需要退款，则将账户余额加上
			if (refund == 1) {
				Record record = Db
						.findFirst(
								"select a.totalmoney,b.proportion,a.b_user_id  from order_detail a left join b_user b on a.b_user_id = b.id where a.id=? limit 1",
								orderId);
				log.debug("record:" + record);
				BigDecimal totalmoney = record.getBigDecimal("totalmoney");
				log.debug("totalmoney" + totalmoney);
				int proportion = record.getInt("proportion");
				log.debug("proportion" + proportion);
				BigDecimal refundMoney = totalmoney.multiply(
						new BigDecimal(proportion)).divide(new BigDecimal(100));
				log.debug("refundMoney:" + refundMoney.toString());

				Db.update(
						"update b_user set  balance = balance+? where id = ?",
						refundMoney, record.getInt("b_user_id"));

			}
		}

		redirect("/order/approvalList");
	}

	/**
	 * 未接取消订单审核
	 */
	public void doCancelNotAcceptApproval() {
		int orderId = getParaToInt("id");
		String content = getPara("content");
		int userId = NumberUtils
				.toInt(getSession().getAttribute("userId") + "");
		Db.update(
				"update order_detail set order_state = 10 , cancel_approval_opinion=? ,cancel_audit=? where id = ?",
				content, userId, orderId);
		redirect("/order/cancelNotAcceptApprovalList");
	}

	/**
	 * 已接取消订单审核
	 */
	public void doCancelAcceptedApproval() {

		int orderId = getParaToInt("id");
		String content = getPara("content");
		int refund = getParaToInt("refund");
		log.debug("refund:" + refund);
		int userId = NumberUtils
				.toInt(getSession().getAttribute("userId") + "");
		log.debug("userId:" + userId);
		Db.update(
				"update order_detail set order_state = 11 , cancel_approval_opinion=? ,cancel_audit=? ,refund = ? where id = ?",
				content, userId, refund, orderId);
		// 如果需要退款，则将账户余额加上
		if (refund == 1) {
			Record record = Db
					.findFirst(
							"select a.totalmoney,b.proportion,a.b_user_id  from order_detail a left join b_user b on a.b_user_id = b.id where a.id=? limit 1",
							orderId);
			log.debug("record:" + record);
			BigDecimal totalmoney = record.getBigDecimal("totalmoney");
			log.debug("totalmoney" + totalmoney);
			int proportion = record.getInt("proportion");
			log.debug("proportion" + proportion);
			BigDecimal refundMoney = totalmoney.multiply(
					new BigDecimal(proportion)).divide(new BigDecimal(100));
			log.debug("refundMoney:" + refundMoney.toString());

			Db.update("update b_user set  balance = balance+? where id = ?",
					refundMoney, record.getInt("b_user_id"));

		}

		redirect("/order/cancelAcceptedList");
	}

	/**
	 * 
	 * @description 已撤销订单列表
	 * @author shevliu
	 * @email shevliu@gmail.com Jul 29, 2012 4:44:15 PM
	 */
	public void cancelList() {
		String id = getPara("id");
		String company=(String) getSession().getAttribute("company");
		String userRole = (String)getSession().getAttribute("userRole");
		
		String from = "from order_detail a left join driver_member b on a.member_id = b.id left join b_user c on a.b_user_id = c.id where a.order_state=5 ";
		if (StringUtils.isNotBlank(id)) {
			from += " and a.id = " + id;
		}
		from = Constants.appendSqlForRoleCom(from, userRole, company);
		from += " order by a.id desc";
		Page<Record> page = Db
				.paginate(
						getParaToInt(0, 1),
						10,
						"select a.*,b.real_name as real_name2,b.user_name,b.cell_phone as cell_phone2,b.sex as sex2 ,b.plage_number as plage_number2, c.name as driver_name , c.job_number,c.phone as driver_phone ",
						from);
		setAttr("page", page);
		render("cancel_list.ftl");
	}

	/**
	 * 
	 * @description 进行中订单列表
	 * @author shevliu
	 * @email shevliu@gmail.com Jul 29, 2012 4:45:37 PM
	 */
	public void processList() {
		//操作员自己所属品牌
		String company=(String) getSession().getAttribute("company");
		int purview=(Integer) getSession().getAttribute("purview");
		String userRole = (String)getSession().getAttribute(Constants.SESSION_USER_ROLE);

        String contentType=(String)getRequest().getParameter("contentType");
        //int purview=(Integer) getSession().getAttribute("purview");
        int pageno=getParaToInt(0, 1);
        if("ajaxHtml".equals(contentType)){
            String pagenum=getRequest().getParameter("page");
            if(pagenum==null||pagenum.equals("")){
                pageno=0;
            }else
                pageno=Integer.parseInt(pagenum);
        }

		String job_number = getPara("job_number");
		String real_name = getPara("real_name");
		String cell_phone = getPara("cell_phone");
		
		String id = getPara("id");
		String from = "from order_detail a left join driver_member b on a.member_id = b.id left join b_user bu on a.b_user_id = bu.id where a.order_state=3 ";
		if (StringUtils.isNotBlank(id)) {
			from += " and a.id = " + id;
		}
		if(StringUtils.isNotBlank(job_number)){
			from += " and bu.job_number = '" + job_number +"'";
		}
		if(StringUtils.isNotBlank(real_name)){
			from += " and a.real_name = '" + real_name +"'";
		}
		if(StringUtils.isNotBlank(cell_phone)){
			from += " and a.cell_phone = '" + cell_phone +"'";
		}
		from = Constants.appendSqlForRoleCom(from, userRole, company);
		
		from += " order by a.id desc";
		Page<Record> page = Db
				.paginate(
						pageno,
						10,
						"select a.*,b.real_name as real_name2,b.user_name,b.cell_phone as cell_phone2,b.sex as sex2 ,b.plage_number as plage_number2 , bu.name as driver_name , bu.job_number,bu.phone as driver_phone, a.order_category_type",
						from);
		setAttr("page", page);
		render("process_list.ftl");
        if(!"ajaxHtml".equals(contentType)) {
            render("process_list.ftl");
        }else{
            Long totalCount=Db.findFirst("select count(1) num "+from).getLong("num");
            Long pageCount=0l;
            if(totalCount%10>0){
                pageCount=totalCount/10+1;
            }else
                pageCount=totalCount/10;
            setAttr("pageCount", pageCount);
            setAttr("totalCount", totalCount);
            render("processAJAX_list.ftl");
        }
	}

	/**
	 * 
	 * @description 临时订单列表
	 * @author shevliu
	 * @email shevliu@gmail.com Jul 29, 2012 4:45:37 PM
	 */
	public void tempList() {
		String id = getPara("id");
		String company=(String) getSession().getAttribute("company");
		String userRole = (String)getSession().getAttribute("userRole");
		
		String from = "from order_detail a left join driver_member b on a.member_id = b.id left join b_user c on a.b_user_id = c.id where a.order_state=7 ";
		if (StringUtils.isNotBlank(id)) {
			from += " and a.id = " + id;
		}
		from = Constants.appendSqlForRoleCom(from, userRole, company);
		
		from += " order by a.id desc";
		Page<Record> page = Db
				.paginate(
						getParaToInt(0, 1),
						10,
						"select a.id , b.user_name,b.real_name,b.cell_phone,b.sex,b.plage_number,a.userarea,a.create_time,a.startpoint,a.endpoint",
						from);
		setAttr("page", page);
		log.debug(page.getList());
		render("temp_list.ftl");
	}

	public void finishList() {
		//操作员自己所属品牌
		String company=(String) getSession().getAttribute("company");
		String userRole = (String)getSession().getAttribute(Constants.SESSION_USER_ROLE);
		String beginDateStr = this.getPara("beginDate");
		String endDateStr = this.getPara("endDate");
		
		String job_number = getPara("job_number");
		String real_name = getPara("real_name");
		String cell_phone = getPara("cell_phone");
		
		String id = getPara("id");
		String from = "from order_detail a left join driver_member b on a.member_id = b.id left join b_user bu on a.b_user_id = bu.id where a.order_state=4 ";
		if (StringUtils.isNotBlank(id)) {
			from += " and a.id = " + id;
			setAttr("id", id);
		}
		if(StringUtils.isNotBlank(job_number)){
			from += " and bu.job_number = '" + job_number +"'";
			setAttr("job_number", job_number);
		}
		if(StringUtils.isNotBlank(real_name)){
			from += " and a.real_name = '" + real_name +"'";
			setAttr("real_name", real_name);
		}
		if(StringUtils.isNotBlank(cell_phone)){
			from += " and a.cell_phone = '" + cell_phone +"'";
			setAttr("cell_phone", cell_phone);
		}
		if(StringUtils.isNotBlank(beginDateStr)){
			setAttr("beginDate", beginDateStr);
			from += " and a.create_time >= '"+beginDateStr+" 00:00:00'";
		}
		if(StringUtils.isNotBlank(endDateStr)){
			Date endDate = TimeUtil.parse(endDateStr, "yyyy-MM-dd", new Date());
			endDate = setTime(endDate, 23, 59, 59, 999);
			
			setAttr("endDate", endDateStr);
			from += " and a.create_time <= '"+endDateStr+" 23:59:59'";
		}
		from = Constants.appendSqlForRoleCom(from, userRole, company);
		
		from += " order by a.id desc";
		Page<Record> page = Db
				.paginate(
						getParaToInt(0, 1),
						10,
						"select a.*,b.real_name as real_name2,b.user_name,b.cell_phone as cell_phone2,b.sex as sex2 ,b.plage_number as plage_number2, bu.name as driver_name , bu.job_number,bu.phone as driver_phone,a.order_category_type",
						from);
		setAttr("page", page);
		setAttr("beginDate",beginDateStr);
		setAttr("endDate",endDateStr);
		
		setAttr("job_number",job_number);
		setAttr("real_name",real_name);
		setAttr("cell_phone",cell_phone);
		
		setAttr("id",id);
		render("finish_list.ftl");
	}

	/**
	 * 未接取消订单列表
	 */
	public void cancelNotAcceptList() {
		String id = getPara("id");
		String company=(String) getSession().getAttribute("company");
		String userRole = (String)getSession().getAttribute("userRole");
		
		String from = "from order_detail a left join driver_member b on a.member_id = b.id left join b_user c on a.b_user_id = c.id where a.order_state=8 ";
		if (StringUtils.isNotBlank(id)) {
			from += " and a.id = " + id;
		}
		from = Constants.appendSqlForRoleCom(from, userRole, company);
		from += " order by a.id desc";
		Page<Record> page = Db
				.paginate(
						getParaToInt(0, 1),
						10,
						"select a.*,b.real_name as real_name2,b.user_name,b.cell_phone as cell_phone2,b.sex as sex2 ,b.plage_number as plage_number2, c.name as driver_name , c.job_number,c.phone as driver_phone",
						from);
		setAttr("page", page);
		render("cancel_not_accept_list.ftl");
	}

	/**
	 * 未接取消订单列表，已审核
	 */
	public void cancelNotAcceptApprovalList() {
		String id = getPara("id");
		String company=(String) getSession().getAttribute("company");
		String userRole = (String)getSession().getAttribute("userRole");
		
		String from = "from order_detail a left join driver_member b on a.member_id = b.id left join b_user c on a.b_user_id = c.id where a.order_state=10 ";
		if (StringUtils.isNotBlank(id)) {
			from += " and a.id = " + id;
		}
		from = Constants.appendSqlForRoleCom(from, userRole, company);
		from += " order by a.id desc";
		Page<Record> page = Db
				.paginate(
						getParaToInt(0, 1),
						10,
						"select a.*,b.real_name as real_name2,b.user_name,b.cell_phone as cell_phone2,b.sex as sex2 ,b.plage_number as plage_number2, c.name as driver_name , c.job_number,c.phone as driver_phone",
						from);
		setAttr("page", page);
		render("cancel_not_accept_approval_list.ftl");
	}

	/**
	 * 已审核订单
	 */
	public void approvalList() {
		String id = getPara("id");
		String userRole = (String) getSession().getAttribute(Constants.SESSION_USER_ROLE);
		String company = (String)getSession().getAttribute("company");
		
		String job_number = getPara("job_number");
		String real_name = getPara("real_name");
		String cell_phone = getPara("cell_phone");
		
		String from = "from order_detail a left join driver_member b on a.member_id = b.id left join b_user bu on a.b_user_id = bu.id where a.order_state in(10, 11, 13) ";
		
		//String from = "from order_detail a where a.order_state in(10, 11, 13)";
		if (StringUtils.isNotBlank(id)) {
			from += " and a.id = " + id;
		}
		if(StringUtils.isNotBlank(job_number)){
			from += " and bu.job_number = '" + job_number +"'";
		}
		if(StringUtils.isNotBlank(real_name)){
			from += " and a.real_name = '" + real_name +"'";
		}
		if(StringUtils.isNotBlank(cell_phone)){
			from += " and a.cell_phone = '" + cell_phone +"'";
		}
		from = Constants.appendSqlForRoleCom(from, userRole, company);
		
		from += " order by a.id desc";
		Page<Record> page = Db
				.paginate(
						getParaToInt(0, 1),
						10,
						"select a.*,b.real_name as real_name2,b.user_name,b.cell_phone as cell_phone2,b.sex as sex2 ,b.plage_number as plage_number2, bu.name as driver_name , bu.job_number,bu.phone as driver_phone,a.order_category_type",
						from);
		setAttr("page", page);
		render("approvalList.ftl");
	}

	/**
	 * 待审核订单
	 */
	public void noApprovalList() {
		//操作员自己所属品牌
		String company=(String) getSession().getAttribute("company");
		int purview=(Integer) getSession().getAttribute("purview");
		String userRole = (String)getSession().getAttribute("userRole");
		
		String job_number = getPara("job_number");
		String real_name = getPara("real_name");
		String cell_phone = getPara("cell_phone");
		
		String id = getPara("id");
		String from = "from order_detail a left join driver_member b on a.member_id = b.id left join b_user bu on a.b_user_id = bu.id where a.order_state in(8, 9, 12) ";
		if (StringUtils.isNotBlank(id)) {
			from += " and a.id = " + id;
		}
		if(StringUtils.isNotBlank(job_number)){
			from += " and bu.job_number = '" + job_number +"'";
		}
		if(StringUtils.isNotBlank(real_name)){
			from += " and a.real_name = '" + real_name +"'";
		}
		if(StringUtils.isNotBlank(cell_phone)){
			from += " and a.cell_phone = '" + cell_phone +"'";
		}
		from = Constants.appendSqlForRoleCom(from, userRole, company);
		
		from += " order by a.id desc";
		Page<Record> page = Db
				.paginate(
						getParaToInt(0, 1),
						10,
						"select a.*,b.real_name as real_name2,b.user_name,b.cell_phone as cell_phone2,b.sex as sex2 ,b.plage_number as plage_number2, bu.name as driver_name , bu.job_number,bu.phone as driver_phone,a.order_category_type",
						from);
		setAttr("page", page);
		render("noApprovalList.ftl");
	}

	/**
	 * 已接取消订单列表
	 */
	public void cancelAcceptedList() {
		String id = getPara("id");
		String from = "from order_detail a left join driver_member b on a.member_id = b.id left join b_user c on a.b_user_id = c.id where a.order_state=9 ";
		if (StringUtils.isNotBlank(id)) {
			from += " and a.id = " + id;
		}
		from += " order by a.id desc";
		Page<Record> page = Db
				.paginate(
						getParaToInt(0, 1),
						10,
						"select a.*,b.real_name as real_name2,b.user_name,b.cell_phone as cell_phone2,b.sex as sex2 ,b.plage_number as plage_number2, c.name as driver_name , c.job_number,c.phone as driver_phone",
						from);
		setAttr("page", page);
		render("cancel_accepted_list.ftl");
	}

	/**
	 * 已接取消订单列表，已审核
	 */
	public void cancelAcceptedApprovalList() {
		//操作员自己所属品牌
		String company=(String) getSession().getAttribute("company");
		String userRole = (String)getSession().getAttribute("userRole");
		int purview=(Integer) getSession().getAttribute("purview");

		String id = getPara("id");
		String from = "from order_detail a left join driver_member b on a.member_id = b.id left join b_user c on a.b_user_id = c.id where a.order_state=11 ";
		if (StringUtils.isNotBlank(id)) {
			from += " and a.id = " + id;
		}
		from = Constants.appendSqlForRoleCom(from, userRole, company);
		
		if(purview==0) //系统管理员
		{
			//全部
		}
		if(purview==1)//品牌操作员
		{
			from +=" and c.job_number regexp '" + company + "[0-9]+'";
		}
		if(purview==2) //品牌客服 2
		{
			from +=" and c.job_number regexp '" + company + "[0-9]+'";
		}

		
		from += " order by a.id desc";
		Page<Record> page = Db
				.paginate(
						getParaToInt(0, 1),
						10,
						"select a.*,b.real_name as real_name2,b.user_name,b.cell_phone as cell_phone2,b.sex as sex2 ,b.plage_number as plage_number2, c.name as driver_name , c.job_number,c.phone as driver_phone",
						from);
		setAttr("page", page);
		render("cancel_accepted_approval_list.ftl");
	}

	/**
	 * 已撤销订单列表-待审核
	 */
	public void driverCancelList() {
		String id = getPara("id");
		String company=(String) getSession().getAttribute("company");
		String userRole = (String)getSession().getAttribute("userRole");
		
		String from = "from order_detail a left join driver_member b on a.member_id = b.id left join b_user c on a.b_user_id = c.id where a.order_state=12 ";
		if (StringUtils.isNotBlank(id)) {
			from += " and a.id = " + id;
		}
		from = Constants.appendSqlForRoleCom(from, userRole, company);
		
		from += " order by a.id desc";
		Page<Record> page = Db
				.paginate(
						getParaToInt(0, 1),
						10,
						"select a.*,b.real_name as real_name2,b.user_name,b.cell_phone as cell_phone2,b.sex as sex2 ,b.plage_number as plage_number2, c.name as driver_name , c.job_number,c.phone as driver_phone",
						from);
		setAttr("page", page);
		render("driver_cancel_list.ftl");
	}

	/**
	 * 已撤销订单列表-已审核
	 */
	public void driverCancelApprovalList() {
		String id = getPara("id");
		String company=(String) getSession().getAttribute("company");
		String userRole = (String)getSession().getAttribute("userRole");
		
		String from = "from order_detail a left join driver_member b on a.member_id = b.id left join b_user c on a.b_user_id = c.id where a.order_state=13 ";
		if (StringUtils.isNotBlank(id)) {
			from += " and a.id = " + id;
		}
		from = Constants.appendSqlForRoleCom(from, userRole, company);
		
		from += " order by a.id desc";
		Page<Record> page = Db
				.paginate(
						getParaToInt(0, 1),
						10,
						"select a.*,b.real_name as real_name2,b.user_name,b.cell_phone as cell_phone2,b.sex as sex2 ,b.plage_number as plage_number2, c.name as driver_name , c.job_number,c.phone as driver_phone",
						from);
		setAttr("page", page);
		render("driver_cancel_approval_list.ftl");
	}

	/**
	 * 投诉列表，待审核
	 * 
	 * @description
	 * @author shevliu
	 * @email shevliu@gmail.com Aug 14, 2012 8:38:02 PM
	 */
	public void complaintList() {
		//操作员自己所属品牌
		String company=(String) getSession().getAttribute("company");
//		int purview=(Integer) getSession().getAttribute("purview");
		String userRole = (String)getSession().getAttribute("userRole");
		
		String job_number = getPara("job_number");
		String real_name = getPara("real_name");
		String cell_phone = getPara("cell_phone");
		
		String id = getPara("id");
		String from = "from order_detail a left join driver_member b on a.member_id = b.id left join b_user bu on a.b_user_id = bu.id where a.ishave_complaint=1 ";
		if (StringUtils.isNotBlank(id)) {
			from += " and a.id = " + id;
		}
		if(StringUtils.isNotBlank(job_number)){
			from += " and bu.job_number = '" + job_number +"'";
		}
		if(StringUtils.isNotBlank(real_name)){
			from += " and a.real_name = '" + real_name +"'";
		}
		if(StringUtils.isNotBlank(cell_phone)){
			from += " and a.cell_phone = '" + cell_phone +"'";
		}
		
		from = Constants.appendSqlForRoleCom(from, userRole, company);
	
		from += " order by a.id desc";
		Page<Record> page = Db
				.paginate(
						getParaToInt(0, 1),
						10,
						"select a.*,b.real_name as real_name2,b.user_name,b.cell_phone as cell_phone2,b.sex as sex2 ,b.plage_number as plage_number2, bu.name as driver_name , bu.job_number,bu.phone as driver_phone,a.order_category_type",
						from);
		setAttr("page", page);
		render("complaint_list.ftl");
	}

	/**
	 * 投诉列表，已审核
	 * 
	 * @description
	 * @author shevliu
	 * @email shevliu@gmail.com Aug 14, 2012 8:38:02 PM
	 */
	public void complaintApprovalList() {
		
		//操作员自己所属品牌
		String company=(String) getSession().getAttribute("company");
//		int purview=(Integer) getSession().getAttribute("purview");
		String userRole = (String)getSession().getAttribute("userRole");
		
		String job_number = getPara("job_number");
		String real_name = getPara("real_name");
		String cell_phone = getPara("cell_phone");
		
		String id = getPara("id");
		String from = "from order_detail a left join driver_member b on a.member_id = b.id left join b_user bu on a.b_user_id = bu.id where a.ishave_complaint=2 ";
		if (StringUtils.isNotBlank(id)) {
			from += " and a.id = " + id;
		}
		if(StringUtils.isNotBlank(job_number)){
			from += " and bu.job_number = '" + job_number +"'";
		}
		if(StringUtils.isNotBlank(real_name)){
			from += " and a.real_name = '" + real_name +"'";
		}
		if(StringUtils.isNotBlank(cell_phone)){
			from += " and a.cell_phone = '" + cell_phone +"'";
		}
		from = Constants.appendSqlForRoleCom(from, userRole, company);
		from += " order by a.id desc";
		Page<Record> page = Db
				.paginate(
						getParaToInt(0, 1),
						10,
						"select a.*,b.real_name as real_name2,b.user_name,b.cell_phone as cell_phone2,b.sex as sex2 ,b.plage_number as plage_number2, bu.name as driver_name , bu.job_number,bu.phone as driver_phone,a.order_category_type",
						from);
		setAttr("page", page);
		render("complaint_approval_list.ftl");
	}

	/**
	 * 
	 * @description 准备派单
	 * @author shevliu
	 * @email shevliu@gmail.com Aug 19, 2012 12:28:52 AM
	 */
	public void assignment() {
	    String company = (String) getSession().getAttribute("company");
	    String ajax=getPara("ajax");
		Long startTime = System.currentTimeMillis();
		int orderId = getParaToInt();
		Order order = Order.dao.findById(orderId);
		String sql = "select *,(SELECT companyname FROM tel_company c WHERE b.license_num=c.company) companyname, (select count(*) from order_detail o where o.b_user_id = b.id and order_state in (1,2,3) ) as acceptNum from b_user b where latitude is not null and longitude is not null and canuse=1 and status=0 and job_number regexp '"+company+"[0-9]+'";
		List<Driver> list = Driver.dao.find(sql);
		List<Driver> tempList = new ArrayList<Driver>();
		String tempDriver = order.getStr("temp_driver");
		if (StringUtils.isNotBlank(tempDriver)) {
			String tempDrivers = tempDriver.replaceAll("#", ",");
			String tempSql = "select * from b_user where id in (" + tempDrivers
					+ ")";
			tempList = Driver.dao.find(tempSql);
			log.debug("tempList:" + tempList);
		}
		
		//String driverSql = "select * from b_user where status=0 and canuse=1 and latitude is not null and longitude is not null";
		//List<Driver> driverList = Driver.dao.find(driverSql);
		BigDecimal startpointLongitude = order.getBigDecimal("startpoint_longitude");
		BigDecimal startpointLatitude = order.getBigDecimal("startpoint_latitude");
		
		Double startLonPoint = null;
		Double startLatPoint = null;
		if(startpointLongitude == null){
			startLonPoint = 0d;
			order.set("startpoint_longitude", 0d);
		}else{
			startLonPoint = startpointLongitude.doubleValue();
		}
		if(startpointLatitude == null){
			startLatPoint = 0d;
			order.set("startpoint_latitude", 0d);
		}else{
			startLatPoint = startpointLatitude.doubleValue();
		}
		
		List<Driver> driverOrderList = new ArrayList<Driver>();
		for(Driver driver : list){
			BigDecimal driverLonPoint = driver.getBigDecimal("longitude");
			BigDecimal driverLatPoint = driver.getBigDecimal("latitude");
			if(driverLonPoint != null
					&& driverLatPoint != null){
				Double distance = LatLonDistance.LantitudeLongitudeDist(startLonPoint, startLatPoint, driverLonPoint.doubleValue(), driverLatPoint.doubleValue());
				driver.put("distance", distance);
				driverOrderList.add(driver);
			}
			
		}
		
		Collections.sort(driverOrderList, new Comparator<Driver>() {
            public int compare(Driver arg0, Driver arg1) {
            	Double distance1 = arg0.getDouble("distance");
            	Double distance2 = arg1.getDouble("distance");
                return distance1.compareTo(distance2);
            }
        });
		int index = 0;
		List<Driver> driverShowList = new ArrayList<Driver>();
		for(Driver driver : driverOrderList){
			if(20 == index){
				break;
			}
			Double newDistance = driver.getDouble("distance")/1000;
			DecimalFormat df = new DecimalFormat("###0.00");
			
			String distanceStr = df.format(newDistance);
			driver.put("distance", distanceStr);
			driverShowList.add(driver);
			index++;
		}
		String inStr = "(";
		for(Driver driver : driverShowList){
			inStr += driver.getInt("id")+",";
		}
		inStr += "0)";
		
		/*StringBuffer from = new StringBuffer();
		from.append(" select a.id,finishNum,cancelNum from b_user a ");
		from.append(" LEFT JOIN tel_company tc ON tc.company = a.license_num ");
		from.append("left join (");
		from.append("select b_user_id,count(*) as finishNum from order_detail where  order_state = 4 group by b_user_id ");
		from.append(" ) b on a.id = b.b_user_id left join ( ");
		from.append("select b_user_id,count(*) as order_count from order_detail group by b_user_id ");
		from.append(" ) d on a.id = d.b_user_id left join ( ");
		from.append("select b_user_id,sum(totalmoney) as sum_money from order_detail where  order_state = 4 group by b_user_id ");
		from.append(" ) e on a.id = e.b_user_id left join ( ");
		from.append("select b_user_id,count(*) as cancelNum from order_detail where  order_state in (8,9,10,11,12,13) group by b_user_id ");
		from.append(") c on a.id = c.b_user_id left join ( ");
		from.append(" select b_user_id,count(*) as acceptNum from order_detail group by b_user_id ");
		from.append(") f on a.id = f.b_user_id where a.id in");
		from.append(inStr);*/
		
		StringBuffer from = new StringBuffer();
		from.append(" select a.id, ");
		from.append(" (select count(*) from order_detail o where o.b_user_id = a.id and order_state = 4 ) as finishNum, ");
		from.append(" (select count(*) from order_detail o where o.b_user_id = a.id and order_state in (8,9,10,11,12,13) ) as cancelNum, ");
		from.append(" (select count(*) from order_detail o where o.b_user_id = a.id and order_state in (1,2,3) ) as acceptNum ");
		from.append(" from b_user a where a.id in");
		from.append(inStr);
		
		List<Driver> driverDemoList = Driver.dao.find(from.toString());
		for(Driver driver : driverShowList){
			for(Driver demodriver : driverDemoList){
				if(driver.getInt("id").equals(demodriver.getInt("id"))){
					driver.put("finishNum", demodriver.getLong("finishNum"));
					driver.put("cancelNum", demodriver.getLong("cancelNum"));
					driver.put("acceptNum", demodriver.getLong("acceptNum"));
					break;
				}
			}
		}
		setAttr("driverShowList", driverShowList);
		setAttr("driverList", list);
		setAttr("order", order);
		setAttr("tempList", tempList);
		log.debug("order:" + order);
		Long endTime = System.currentTimeMillis();
		System.out.println(endTime - startTime);
		if("1".equals(ajax)){
		    renderJson();
		    return;
		}
		render("../map/order_assignment.ftl");
	}
	
	//点击定位后 就显示司机用这个
	public void ajaxAssignment() {
	    String company = (String) getSession().getAttribute("company");
		Long startTime = System.currentTimeMillis();
		String sql = "select *,(SELECT companyname FROM tel_company c WHERE b.license_num=c.company) companyname, (select count(*) from order_detail o where o.b_user_id = b.id and order_state in (1,2,3) ) as acceptNum from b_user b where latitude is not null and longitude is not null and canuse=1 and status=0 and job_number regexp '"+company+"[0-9]+'";
		List<Driver> list = Driver.dao.find(sql);
		
		//String driverSql = "select * from b_user where status=0 and canuse=1 and latitude is not null and longitude is not null";
		//List<Driver> driverList = Driver.dao.find(driverSql);
		BigDecimal startpointLongitude =new BigDecimal( getPara("order.startpoint_longitude"));
		BigDecimal startpointLatitude = new BigDecimal(getPara("order.startpoint_latitude"));
		
		Double startLonPoint = null;
		Double startLatPoint = null;
		if(startpointLongitude == null){
			startLonPoint = 0d;
		}else{
			startLonPoint = startpointLongitude.doubleValue();
		}
		if(startpointLatitude == null){
			startLatPoint = 0d;
		}else{
			startLatPoint = startpointLatitude.doubleValue();
		}
		
		List<Driver> driverOrderList = new ArrayList<Driver>();
		for(Driver driver : list){
			BigDecimal driverLonPoint = driver.getBigDecimal("longitude");
			BigDecimal driverLatPoint = driver.getBigDecimal("latitude");
			if(driverLonPoint != null
					&& driverLatPoint != null){
				Double distance = LatLonDistance.LantitudeLongitudeDist(startLonPoint, startLatPoint, driverLonPoint.doubleValue(), driverLatPoint.doubleValue());
				driver.put("distance", distance);
				driverOrderList.add(driver);
			}
			
		}
		
		Collections.sort(driverOrderList, new Comparator<Driver>() {
            public int compare(Driver arg0, Driver arg1) {
            	Double distance1 = arg0.getDouble("distance");
            	Double distance2 = arg1.getDouble("distance");
                return distance1.compareTo(distance2);
            }
        });
		int index = 0;
		List<Driver> driverShowList = new ArrayList<Driver>();
		for(Driver driver : driverOrderList){
			if(20 == index){
				break;
			}
			Double newDistance = driver.getDouble("distance")/1000;
			DecimalFormat df = new DecimalFormat("###0.00");
			
			String distanceStr = df.format(newDistance);
			driver.put("distance", distanceStr);
			driverShowList.add(driver);
			index++;
		}
		String inStr = "(";
		for(Driver driver : driverShowList){
			inStr += driver.getInt("id")+",";
		}
		inStr += "0)";
		
		/*StringBuffer from = new StringBuffer();
		from.append(" select a.id,finishNum,cancelNum from b_user a ");
		from.append(" LEFT JOIN tel_company tc ON tc.company = a.license_num ");
		from.append("left join (");
		from.append("select b_user_id,count(*) as finishNum from order_detail where  order_state = 4 group by b_user_id ");
		from.append(" ) b on a.id = b.b_user_id left join ( ");
		from.append("select b_user_id,count(*) as order_count from order_detail group by b_user_id ");
		from.append(" ) d on a.id = d.b_user_id left join ( ");
		from.append("select b_user_id,sum(totalmoney) as sum_money from order_detail where  order_state = 4 group by b_user_id ");
		from.append(" ) e on a.id = e.b_user_id left join ( ");
		from.append("select b_user_id,count(*) as cancelNum from order_detail where  order_state in (8,9,10,11,12,13) group by b_user_id ");
		from.append(") c on a.id = c.b_user_id left join ( ");
		from.append(" select b_user_id,count(*) as acceptNum from order_detail group by b_user_id ");
		from.append(") f on a.id = f.b_user_id where a.id in");
		from.append(inStr);*/
		
		StringBuffer from = new StringBuffer();
		from.append(" select a.id, ");
		from.append(" (select count(*) from order_detail o where o.b_user_id = a.id and order_state = 4 ) as finishNum, ");
		from.append(" (select count(*) from order_detail o where o.b_user_id = a.id and order_state in (8,9,10,11,12,13) ) as cancelNum, ");
		from.append(" (select count(*) from order_detail o where o.b_user_id = a.id and order_state in (1,2,3) ) as acceptNum ");
		from.append(" from b_user a where a.id in");
		from.append(inStr);
		
		List<Driver> driverDemoList = Driver.dao.find(from.toString());
		for(Driver driver : driverShowList){
			for(Driver demodriver : driverDemoList){
				if(driver.getInt("id").equals(demodriver.getInt("id"))){
					driver.put("finishNum", demodriver.getLong("finishNum"));
					driver.put("cancelNum", demodriver.getLong("cancelNum"));
					driver.put("acceptNum", demodriver.getLong("acceptNum"));
					break;
				}
			}
		}
		setAttr("driverShowList", driverShowList);
		setAttr("driverList", list);
		Long endTime = System.currentTimeMillis();
		System.out.println(endTime - startTime);
		
	    renderJson();
	    return;

	}

	/**
	 * 派单
	 * 
	 * @description
	 * @author shevliu
	 * @email shevliu@gmail.com Aug 14, 2012 10:51:11 PM
	 */
	@Before(Tx.class)
	public void saveJob() {
		File configFile = new File(PathUtil.getWebRootPath(),
				"/WEB-INF/config.properties");
		SmsUtil.init(configFile);

		String driver_id_para = getPara("driver_id");
		
		String[] driver_id_arr = driver_id_para.split(",");
		
		Integer[] driverIds = new Integer[driver_id_arr.length];
		for(int i =0;i<driver_id_arr.length;i++){
			driverIds[i]=Integer.parseInt(driver_id_arr[i]);
		}
		Integer driverRateKm = getParaToInt("driverRateKm");
		if(driverRateKm==null)
			driverRateKm=2;

		
//		Integer[] driverIds = getParaValuesToInt("driver_id");
		int orderId = getParaToInt("order_id");
		Date now = new Date();
		Db.update("delete from order_job where order_id = ?", orderId);
		String sql = "insert into order_job(order_id , b_user_id , job_time ,status) values ( ? , ? , ? , ?)";
		Order order = Order.dao.findById(orderId);
		
		String company = (String) getSession().getAttribute("company");
		String companyname = (String) getSession().getAttribute("myCompanyName");
		String userName = (String) getSession().getAttribute("userName");
		int sysUserId = (Integer) getSession().getAttribute("userId");
		
		for (Integer driverId : driverIds) {
			Db.update(sql, orderId, driverId, now, 0);
			Driver driver = Driver.dao.findById(driverId);
			// AccessConnection access = new AccessConnection();
			String content = "出发地：" + order.getStr("startpoint") + "，目的地："
					+ order.getStr("endpoint") + "，距离："
					+ order.getBigDecimal("kilometre").toString() + "公里，价格："
					+ order.getBigDecimal("totalmoney").toString()
					+ "元，快去接收吧！";
			
			String deviceId = driver.getStr("device_id");
			log.debug("deviceId:" + deviceId);
			if(!StringUtils.isEmpty(deviceId)){
				Map<String, String> paramsMap = new HashMap<String, String>();
				paramsMap.put("orderId", orderId+"");
				paramsMap.put("kilometre", order.getStr("kilometer"));
				paramsMap.put("from_source", order.getStr("from_source"));
				if(order.getBigDecimal("startpoint_latitude")==null)
					paramsMap.put("startpoint_latitude", "0");
				else
					paramsMap.put("startpoint_latitude", order.getBigDecimal("startpoint_latitude").toString());
				if(order.getTimestamp("create_time")==null)
					paramsMap.put("create_time", "");
				else
					paramsMap.put("create_time", order.getTimestamp("create_time").toString());
				paramsMap.put("pay_type", order.getInt("pay_type").toString());
				paramsMap.put("order_type", order.getInt("order_type").toString());
				paramsMap.put("totalmoney", order.getBigDecimal("totalmoney").toString());
				paramsMap.put("source", order.getStr("source"));
		        paramsMap.put("driver_got", order.getBigDecimal("driver_got").toString());
		        paramsMap.put("startpoint", order.getStr("startpoint"));
		        if(order.getTimestamp("publish_time")==null)
		        	paramsMap.put("publish_time","");
		        else
		        	paramsMap.put("publish_time",order.getTimestamp("publish_time").toString());
		        //paramsMap.put("reFlag", "0");
		        paramsMap.put("cityId", "");
		        if(order.getLong("order_state")==null)
		        	paramsMap.put("order_state", "0");
		        else
		        	paramsMap.put("order_state", order.getLong("order_state").toString());
		        if(order.getTimestamp("point_time")==null){
		        	paramsMap.put("point_time", "");
		        	paramsMap.put("reFlag", "0");
		        }
		        else{
		        	paramsMap.put("point_time", order.getTimestamp("point_time").toString());
		        	if(TimeUtil.compareTime(order.getTimestamp("point_time").toString()))
                        paramsMap.put("reFlag", "1");
                    else{
                        paramsMap.put("reFlag", "0");
                    }
		        }
		        paramsMap.put("endpoint", order.getStr("endpoint"));
		        paramsMap.put("startpoint_longitude", order.getBigDecimal("startpoint_longitude").toString());
		        if(order.getBigDecimal("charges")==null)
		        	paramsMap.put("charges", "0");
		        else
		        	paramsMap.put("charges", order.getBigDecimal("charges").toString());
		        paramsMap.put("t", "order:"+ order.getStr("order_category_type").toLowerCase()+":accept");
		        paramsMap.put("member_id", order.getInt("member_id").toString());
		        paramsMap.put("b_user_id", order.getInt("b_user_id").toString());
		        paramsMap.put("order_category_type", order.getStr("order_category_type"));
				try {
					PushTokenUtils.sendPush(content, deviceId, JpushType.order_driver_accept, paramsMap);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			/*
			 * String smsSql = "insert into OutBox (Mbno,Msg) values ('" +
			 * driver.getStr("phone") + "','" + content + "')";
			 */
			//SmsUtil.sendMessage(driver.getStr("phone"), content);
			// access.update(smsSql);
			
			Db.update("insert into operator_log(sys_user_id,b_user_id,log_type,remarks,company,companyname,sys_user_name,order_id,create_time) values(?,?,?,?,?,?,?,?,?)",
					sysUserId,driverId,TypeConstant.OperatorType.ORDER_ASSIGN.name(),
					TypeConstant.OperatorType.ORDER_ASSIGN.getTypeName(),company,companyname,userName,orderId,new Date());
		}
		Db.update("update order_detail set order_state = 0 ,publish_time=now(), from_source=? where id = ? ",
				TypeConstant.OrderFromSource.ADMIN.name(), orderId);
		
		//加入对该订单的后续查看线程(延时3)
		OrderRunnable m1=new OrderRunnable(""+orderId,orderId,driverRateKm,company,OrderRunnable.FORCE_MODE,2,driver_id_para);
		Thread t1=new Thread(m1);
		t1.start();
		
		String orderType = order.getStr("order_category_type");
		if(OrderType.UNLOCK.name().equals(orderType)){
			redirect("/categoryorder/unlockList");
		}else if(OrderType.DELIVERY.name().equals(orderType)){
			redirect("/categoryorder/deliveryList");
		}else if(OrderType.PARK.name().equals(orderType)){
			redirect("/categoryorder/parkList");
		}else{			
			redirect("/order/acceptList");
		}
	}
	
	public static void my(String driver_id,int orderId,int times){
		//String driver_id_para = getPara("driver_id");
		
		String[] driver_id_arr = driver_id.split(",");
		
		Integer[] driverIds = new Integer[driver_id_arr.length];
		for(int i =0;i<driver_id_arr.length;i++){
			driverIds[i]=Integer.parseInt(driver_id_arr[i]);
		}
		
//		Integer[] driverIds = getParaValuesToInt("driver_id");
		//int orderId = getParaToInt("order_id");
		Date now = new Date();
		//Db.update("delete from order_job where order_id = ?", orderId);
		String sql = "insert into order_job(order_id , b_user_id , job_time ,status) values ( ? , ? , ? , ?)";
		Order order = Order.dao.findById(orderId);
		
		/*String company = (String) getSession().getAttribute("company");
		String companyname = (String) getSession().getAttribute("myCompanyName");
		String userName = (String) getSession().getAttribute("userName");
		int sysUserId = (Integer) getSession().getAttribute("userId");*/
		long order_state=order.getLong("order_state");
		if(order_state==0 || order_state==6){
			for (Integer driverId : driverIds) {
				Db.update(sql, orderId, driverId, now, 0);
				Driver driver = Driver.dao.findById(driverId);
				// AccessConnection access = new AccessConnection();
				String content = "出发地：" + order.getStr("startpoint") + "，目的地："
						+ order.getStr("endpoint") + "，距离："
						+ order.getBigDecimal("kilometre").toString() + "公里，价格："
						+ order.getBigDecimal("totalmoney").toString()
						+ "元，快去接收吧！";
				
				String deviceId = driver.getStr("device_id");
				log.debug("deviceId:" + deviceId);
				if(!StringUtils.isEmpty(deviceId)){
					Map<String, String> paramsMap = new HashMap<String, String>();
					paramsMap.put("orderId", orderId+"");
					paramsMap.put("kilometre", order.getStr("kilometer"));
					paramsMap.put("from_source", order.getStr("from_source"));
					if(order.getBigDecimal("startpoint_latitude")==null)
						paramsMap.put("startpoint_latitude", "0");
					else
						paramsMap.put("startpoint_latitude", order.getBigDecimal("startpoint_latitude").toString());
					if(order.getTimestamp("create_time")==null)
						paramsMap.put("create_time", "");
					else
						paramsMap.put("create_time", order.getTimestamp("create_time").toString());
					paramsMap.put("pay_type", order.getInt("pay_type").toString());
					paramsMap.put("order_type", order.getInt("order_type").toString());
					paramsMap.put("totalmoney", order.getBigDecimal("totalmoney").toString());
					paramsMap.put("source", order.getStr("source"));
			        paramsMap.put("driver_got", order.getBigDecimal("driver_got").toString());
			        paramsMap.put("startpoint", order.getStr("startpoint"));
			        if(order.getTimestamp("publish_time")==null)
			        	paramsMap.put("publish_time","");
			        else
			        	paramsMap.put("publish_time",order.getTimestamp("publish_time").toString());
			        //paramsMap.put("reFlag", "0");
			        paramsMap.put("cityId", "");
			        if(order.getLong("order_state")==null)
			        	paramsMap.put("order_state", "0");
			        else
			        	paramsMap.put("order_state", order.getLong("order_state").toString());
			        if(order.getTimestamp("point_time")==null){
			        	paramsMap.put("point_time", "");
			        	paramsMap.put("reFlag", "0");
			        }
			        else{
			        	paramsMap.put("point_time", order.getTimestamp("point_time").toString());
			        	if(TimeUtil.compareTime(order.getTimestamp("point_time").toString()))
	                        paramsMap.put("reFlag", "1");
	                    else{
	                        paramsMap.put("reFlag", "0");
	                    }
			        }
			        paramsMap.put("endpoint", order.getStr("endpoint"));
			        paramsMap.put("startpoint_longitude", order.getBigDecimal("startpoint_longitude").toString());
			        if(order.getBigDecimal("charges")==null)
			        	paramsMap.put("charges", "0");
			        else
			        	paramsMap.put("charges", order.getBigDecimal("charges").toString());
			        paramsMap.put("t", "order:"+ order.getStr("order_category_type").toLowerCase()+":accept");
			        paramsMap.put("member_id", order.getInt("member_id").toString());
			        paramsMap.put("b_user_id", order.getInt("b_user_id").toString());
			        paramsMap.put("order_category_type", order.getStr("order_category_type"));
					try {
						PushTokenUtils.sendPush(content, deviceId, JpushType.order_driver_accept, paramsMap);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				/*
				 * String smsSql = "insert into OutBox (Mbno,Msg) values ('" +
				 * driver.getStr("phone") + "','" + content + "')";
				 */
				//SmsUtil.sendMessage(driver.getStr("phone"), content);
				// access.update(smsSql);
				
				/*Db.update("insert into operator_log(sys_user_id,b_user_id,log_type,remarks,company,companyname,sys_user_name,order_id,create_time) values(?,?,?,?,?,?,?,?,?)",
						sysUserId,driverId,TypeConstant.OperatorType.ORDER_ASSIGN.name(),
						TypeConstant.OperatorType.ORDER_ASSIGN.getTypeName(),company,companyname,userName,orderId,new Date());*/
			}
			Db.update("update order_detail set order_state = 0 ,publish_time=now(), from_source=? where id = ? ",
					TypeConstant.OrderFromSource.ADMIN.name(), orderId);
			
			//加入对该订单的后续查看线程(延时3)
			OrderRunnable m1=new OrderRunnable(""+orderId,orderId,0,"",OrderRunnable.FORCE_MODE,times+1,driver_id);
			Thread t1=new Thread(m1);
			t1.start();
		}
	}
	
	/**
	 * 批量派单---异步请求
	 */
	public void saveJobAjax() {
//		File configFile = new File(PathUtil.getWebRootPath(),
//				"/WEB-INF/config.properties");
//		SmsUtil.init(configFile);
//
//		Integer[] driverIds = getParaValuesToInt("driver_id");
//		int orderId = getParaToInt("order_id");
//		Date now = new Date();
//		Db.update("delete from order_job where order_id = ?", orderId);
//		String sql = "insert into order_job(order_id , b_user_id , job_time ,status) values ( ? , ? , ? , ?)";
//		Order order = Order.dao.findById(orderId);
//		
//		String company = (String) getSession().getAttribute("company");
//		String companyname = (String) getSession().getAttribute("myCompanyName");
//		String userName = (String) getSession().getAttribute("userName");
//		int sysUserId = (Integer) getSession().getAttribute("userId");
//		
//		for (Integer driverId : driverIds) {
//			Db.update(sql, orderId, driverId, now, 0);
//			Driver driver = Driver.dao.findById(driverId);
//			// AccessConnection access = new AccessConnection();
//			String content = "出发地：" + order.getStr("startpoint") + "，目的地："
//					+ order.getStr("endpoint") + "，距离："
//					+ order.getBigDecimal("kilometre").toString() + "公里，价格："
//					+ order.getBigDecimal("totalmoney").toString()
//					+ "元，快去接收吧！";
//			
//			String deviceId = driver.getStr("device_id");
//			log.debug("deviceId:" + deviceId);
//			if(!StringUtils.isEmpty(deviceId)){
//				Map<String, String> paramsMap = new HashMap<String, String>();
//				paramsMap.put("orderId", orderId+"");
//				try {
//					PushTokenUtils.sendPush(content, deviceId, JpushType.order_driver_accept, paramsMap);
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
//			}
//			/*
//			 * String smsSql = "insert into OutBox (Mbno,Msg) values ('" +
//			 * driver.getStr("phone") + "','" + content + "')";
//			 */
//			//SmsUtil.sendMessage(driver.getStr("phone"), content);
//			// access.update(smsSql);
//			
//			Db.update("insert into operator_log(sys_user_id,b_user_id,log_type,remarks,company,companyname,sys_user_name,order_id,create_time) values(?,?,?,?,?,?,?,?,?)",
//					sysUserId,driverId,TypeConstant.OperatorType.ORDER_ASSIGN.name(),
//					TypeConstant.OperatorType.ORDER_ASSIGN.getTypeName(),company,companyname,userName,orderId,new Date());
//		}
//		Db.update("update order_detail set order_state = 0 ,publish_time=now(), from_source=? where id = ? ",
//				TypeConstant.OrderFromSource.ADMIN.name(), orderId);
		Map<String,Object> result = new HashMap<String,Object>();
		
		result.put("orderType", "DRIVER");
		
		renderJson("orderType", "DRIVER");
		
//		String orderType = order.getStr("order_category_type");
//		if(OrderType.UNLOCK.name().equals(orderType)){
//			redirect("/categoryorder/unlockList");
//		}else if(OrderType.DELIVERY.name().equals(orderType)){
//			redirect("/categoryorder/deliveryList");
//		}else if(OrderType.PARK.name().equals(orderType)){
//			redirect("/categoryorder/parkList");
//		}else{			
//			redirect("/order/acceptList");
//		}
	}
	
	
	

	/**
	 * 查询某会员所下订单
	 */
	public void memberOrder() {
		int memberId = getParaToInt();
		List<Order> list = Order.dao
				.find("select a.*,c.name as driver_name , c.job_number,c.phone as driver_phone from order_detail a  left join b_user c on a.b_user_id = c.id where member_id = ? order by id desc",
						memberId);
		
		Member member = Member.dao.findFirst("select * from driver_member where status=1 and id=?" , memberId);
		
		Record rec = Db	.findFirst(
			"select (select count(*) from order_detail where member_id =?) order_count," +
			" (select count(*) from order_detail  where member_id =?  and cancel is not null) cancel_order_count ," +
			" (select count(*) from order_detail where member_id =? and DATE_FORMAT(create_time, '%Y%m' )= DATE_FORMAT(CURDATE(), '%Y%m') ) month_order_count ," +
			" (select ifnull(sum(totalmoney),0) from order_detail where member_id =? and order_state=4 ) finishmoney;",
			memberId, memberId,memberId,memberId);
		setAttr("order_count",rec.getLong("order_count"));
		setAttr("cancel_order_count",rec.getLong("cancel_order_count"));
		setAttr("month_order_count",rec.getLong("month_order_count"));
		setAttr("finishmoney",rec.getBigDecimal("finishmoney"));
		
		setAttr("member", member);
		
		
		
		setAttr("list", list);
		log.debug("list:" + list.size());
		render("member_order_list.ftl");

	}

	/**
	 * 查看订单轨迹
	 */
	public void trajectory() {
		int orderId = getParaToInt();
		List<OrderTrajectory> list = OrderTrajectory.dao
				.find("select * from order_trajectory where order_id = ? order by id ",
						orderId);
		StringBuffer sb = new StringBuffer();
		for (OrderTrajectory point : list) {
			sb.append("new BMap.Point(");
			sb.append(point.getBigDecimal("longitude"));
			sb.append(",");
			sb.append(point.getBigDecimal("latitude"));
			sb.append("),");
		}
		if (list.size() > 0) {
			setAttr("points", sb.toString().substring(0, sb.length() - 1));
			log.debug("points:" + sb.toString().substring(0, sb.length() - 1));
		}
		setAttr("list", list);
		render("../map/order_trajectory.ftl");
	}

	/**
	 * 
	 * @description 导出待分派订单
	 * @author shevliu
	 * @email shevliu@gmail.com Aug 1, 2012 10:09:02 PM
	 */
	public void assignExcel() {
		excel("6");
	}

	/**
	 * 
	 * @description 导出待接受订单
	 * @author shevliu
	 * @email shevliu@gmail.com Aug 1, 2012 10:09:02 PM
	 */
	public void acceptExcel() {
		excel("0");
	}

	/**
	 * 导出待已接受订单
	 */
	public void acceptedExcel() {
		excel("1");
	}

	public void excel2() {
		excel("2");
	}

	/**
	 * 
	 * @description 导出正在执行订单
	 * @author shevliu
	 * @email shevliu@gmail.com Aug 1, 2012 10:09:02 PM
	 */
	public void processExcel() {
		excel("3");
	}

	/**
	 * 
	 * @description 导出已完成订单
	 * @author shevliu
	 * @email shevliu@gmail.com Aug 1, 2012 10:09:02 PM
	 */
	public void finishExcel() {
		excel("4");
	}

	public void excel6() {
		excel("6");
	}

	public void excel7() {
		excel("7");
	}

	public void excel8() {
		excel("8");
	}

	public void excel9() {
		excel("9");
	}

	public void excel10() {
		excel("10");
	}

	public void excel11() {
		excel("11");
	}

	public void excel12() {
		excel("12");
	}

	public void excel13() {
		excel("13");
	}

	/**
	 * 导出投诉列表
	 * 
	 * @description
	 * @author shevliu
	 * @email shevliu@gmail.com Aug 14, 2012 9:38:47 PM
	 */
	public void haveComplaintExcel() {
		excel("-100");
	}

	/**
	 * 导出投诉已处理列表
	 * 
	 * @description
	 * @author shevliu
	 * @email shevliu@gmail.com Aug 14, 2012 9:38:47 PM
	 */
	public void ComplaintApprovalExcel() {
		excel("-101");
	}

	private void excel(String state) {
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet();
		HSSFRow row = sheet.createRow((short) 0);
		row.createCell(0).setCellValue("单号");
		row.createCell(1).setCellValue("客户姓名");
		row.createCell(2).setCellValue("客户手机");
		row.createCell(3).setCellValue("客户性别");
		row.createCell(4).setCellValue("车牌号码");
		row.createCell(5).setCellValue("所在区域");
		row.createCell(6).setCellValue("地号");
		row.createCell(7).setCellValue("起点");
		row.createCell(8).setCellValue("终点");
		row.createCell(9).setCellValue("里程");
		row.createCell(10).setCellValue("总金额");
		row.createCell(11).setCellValue("支付方式");
		row.createCell(12).setCellValue("订单类型");
		row.createCell(13).setCellValue("代驾员姓名");
		row.createCell(14).setCellValue("代驾员工号");
		row.createCell(15).setCellValue("联系方式");
		row.createCell(16).setCellValue("下单时间");
		row.createCell(17).setCellValue("发布时间");
		row.createCell(18).setCellValue("接受时间");
		row.createCell(19).setCellValue("到达时间");
		row.createCell(20).setCellValue("开始代驾时间");
		row.createCell(21).setCellValue("结束时间");
		row.createCell(22).setCellValue("取消原因");
		row.createCell(23).setCellValue("审核意见");
		row.createCell(24).setCellValue("投诉");
		row.createCell(25).setCellValue("处理意见");
		List<Record> list;
		String sql = "select a.*,b.user_name , b.real_name as real_name2 ,b.cell_phone as cell_phone2,b.sex as sex2,b.plage_number  as plage_number2 , c.name as driver_name , c.job_number,c.phone as driver_phone from order_detail a left join driver_member b  on a.member_id = b.id left join b_user c on a.b_user_id = c.id ";

		if ("-100".equals(state)) {// 已投诉
			sql += " where a.ishave_complaint=1  order by a.id desc";
		} else if ("-10".equals(state)) { // 投诉已处理
			sql += " where a.ishave_complaint=2  order by a.id desc";
		} else if("4".equals(state)){//已完成
			sql += " where a.order_state in(" + state + ") ";
			String company=(String) getSession().getAttribute("company");
			
			String userRole = (String)getSession().getAttribute("userRole");
			if(!"admin".equals(userRole)){
				sql+=" and a.source='"+company+"'";
			}
			String begindate=getPara("beginDate");
			String endDate=getPara("endDate");
			String id=getPara("id");
			String real_name=getPara("real_name");
			String cell_phone=getPara("cell_phone");
			String job_number=getPara("job_number");
			if(StringUtils.isNotBlank(begindate)){
				sql += " and a.create_time >= '"+begindate+" 00:00:00'";
			}
			if(StringUtils.isNotBlank(endDate)){				
				sql += " and a.create_time <= '"+endDate+" 23:59:59'";
			}
			if (StringUtils.isNotBlank(id)) {
				sql += " and a.id = " + id;
			}
			if(StringUtils.isNotBlank(job_number)){
				sql += " and c.job_number = '" + job_number +"'";
			}
			if(StringUtils.isNotBlank(real_name)){
				sql += " and a.real_name = '" + real_name +"'";
			}
			if(StringUtils.isNotBlank(cell_phone)){
				sql += " and a.cell_phone = '" + cell_phone +"'";
			}
			sql+=" order by a.id desc";
			
		} else {
			sql += " where a.order_state in(" + state + ") order by a.id desc";
			list = Db.find(sql);
		}
		list = Db.find(sql);

		for (int i = 0; i < list.size(); i++) {
			HSSFRow r = sheet.createRow(i + 1);
			Record record = list.get(i);
			try {
				int memberId = record.getInt("member_id");
				int sex = 0;
				r.createCell(0).setCellValue(record.getInt("id"));
				if (memberId == 0) {
					r.createCell(1).setCellValue(record.getStr("real_name"));
					r.createCell(2).setCellValue(record.getStr("cell_phone"));
					sex = (record.get("sex") == null ? 2:record.getInt("sex"));
					r.createCell(4).setCellValue(record.getStr("plage_number"));
				} else {
					r.createCell(1).setCellValue(record.getStr("real_name2"));
					r.createCell(2).setCellValue(record.getStr("cell_phone2"));
					sex = (record.get("sex2") == null ? 2:record.getInt("sex2"));
					r.createCell(4).setCellValue(record.getStr("plage_number2"));
				}
				if (sex == 0) {
					r.createCell(3).setCellValue("男");
				} else if (sex == 1) {
					r.createCell(3).setCellValue("女");
				} else {
					r.createCell(3).setCellValue("未知");
				}
				r.createCell(5).setCellValue(record.getStr("userarea"));
				r.createCell(6).setCellValue(record.getStr("area_num"));
				r.createCell(7).setCellValue(record.getStr("startpoint"));
				r.createCell(8).setCellValue(record.getStr("endpoint"));
				r.createCell(9).setCellValue(
						record.getBigDecimal("kilometre").toString());
				r.createCell(10).setCellValue(
						record.getBigDecimal("totalmoney").toString());
				int payType = record.getInt("pay_type");
				if (payType == 0) {
					r.createCell(11).setCellValue("现金");
				} else if (payType == 1) {
					r.createCell(11).setCellValue("企业支付");
				} else if (payType == 2) {
					r.createCell(11).setCellValue("VIP支付");
				} else {
					r.createCell(11).setCellValue("免费客户");
				}
				int orderType = record.getInt("order_type");
				if (orderType == 0) {
					r.createCell(12).setCellValue("普通");
				} else if (orderType == 1) {
					r.createCell(12).setCellValue("企业订单");
				} else if (orderType == 2) {
					r.createCell(12).setCellValue("酒店订单");
				} else if (orderType == 3) {
					r.createCell(12).setCellValue("KTV订单");
				}

				r.createCell(13).setCellValue(record.getStr("driver_name"));
				r.createCell(14).setCellValue(record.getStr("job_number"));
				r.createCell(15).setCellValue(record.getStr("driver_phone"));

				Timestamp ts1 = record.getTimestamp("create_time");
				r.createCell(16).setCellValue(ts1 == null ? "" : ts1.toString());
				Timestamp ts2 = record.getTimestamp("publish_time");
				r.createCell(17).setCellValue(ts2 == null ? "" : ts2.toString());
				Timestamp ts3 = record.getTimestamp("accept_time");
				r.createCell(18).setCellValue(ts3 == null ? "" : ts3.toString());
				Timestamp ts4 = record.getTimestamp("arrived_time");
				r.createCell(19).setCellValue(ts4 == null ? "" : ts4.toString());
				Timestamp ts5 = record.getTimestamp("driver_begin_time");
				r.createCell(20).setCellValue(ts5 == null ? "" : ts5.toString());
				Timestamp ts6 = record.getTimestamp("driver_finish_time");
				r.createCell(21).setCellValue(ts6 == null ? "" : ts6.toString());

				String cancel = record.getStr("cancel") == null ? "" : record
						.getStr("cancel");
				String cancelDriver = record.getStr("cancel_driver") == null ? ""
						: record.getStr("cancel_driver");
				r.createCell(22).setCellValue(cancel + cancelDriver);
				r.createCell(23).setCellValue(
						record.getStr("cancel_approval_opinion"));
				r.createCell(24).setCellValue(record.getStr("complaint_content"));
				r.createCell(25).setCellValue(
						record.getStr("complain_approval_opinion"));
			} catch (Exception e) {
				log.error(e.getMessage(), e);
			}
			
		}
		PathUtil.getWebRootPath();
		String fileName = PathUtil.getWebRootPath() + "/excel/"
				+ System.currentTimeMillis() + "_" + new Random().nextLong()
				+ ".xls";
		File f = new File(fileName);
		log.debug("file path:" + f.getAbsolutePath());
		FileOutputStream fOut;
		try {
			fOut = new FileOutputStream(fileName);
			workbook.write(fOut);
			fOut.flush();
			fOut.close();
		} catch (Exception e) {
			throw new RuntimeException("导出excel失败，请稍后再试", e);
		}
		renderFile(f);
	}

	public void count() {
		String company=(String) getSession().getAttribute("company");
		String userRole = (String) getSession().getAttribute("userRole");
		
		Date now = new Date();
		String today = TimeUtil.format(now, "yyyy-MM-dd") + " 00:00:00";
		log.debug("today:" + today);
		
		String sqlTotal = "select count(0) as num from order_detail a where create_time >= ?";
		sqlTotal = Constants.appendSqlForRoleCom(sqlTotal, userRole, company);
		long total = Db.findFirst(sqlTotal, today).getLong("num");

		String sqlTemp = "select count(0) as num from order_detail a where create_time >= ? and order_state=7";
		sqlTemp = Constants.appendSqlForRoleCom(sqlTemp, userRole, company);
		long temp = Db.findFirst(sqlTemp, today).getLong("num");

		String sqlAssignment = "select count(0) as num from order_detail a where create_time >= ? and order_state=6";
		sqlAssignment = Constants.appendSqlForRoleCom(sqlAssignment, userRole, company);
		long assignment = Db.findFirst(sqlAssignment, today).getLong("num");

		String sqlAccept = "select count(0) as num from order_detail a where create_time >= ? and order_state=0";
		sqlAccept = Constants.appendSqlForRoleCom(sqlAccept, userRole, company);
		long accept = Db.findFirst(sqlAccept, today).getLong("num");

		String sqlProcess = "select count(0) as num from order_detail a where create_time >= ? and  order_state=3";
		sqlProcess = Constants.appendSqlForRoleCom(sqlProcess, userRole, company);
		long process = Db.findFirst(sqlProcess, today).getLong("num");

		String finishProcess = "select count(0) as num from order_detail a where create_time >= ? and order_state=4";
		finishProcess = Constants.appendSqlForRoleCom(finishProcess, userRole, company);
		long finish = Db.findFirst(finishProcess, today).getLong("num");

		String cancelProcess = "select count(0) as num from order_detail a where create_time >= ? and order_state in (8,9,10,11,12,13)";
		cancelProcess = Constants.appendSqlForRoleCom(cancelProcess, userRole, company);
		long cancel = Db.findFirst(cancelProcess, today).getLong("num");
		
		//String userMessage = "SELECT COUNT(*) as num FROM tel_company_message WHERE create_time >DATE_ADD(CURDATE(),INTERVAL -DAY(CURDATE())+1 DAY) AND create_time<LAST_DAY(CURDATE()) AND COMPANY='"+company+"'";
		//long messageUserCount = Db.findFirst(userMessage).getLong("num");
		
		String totalMessage = "SELECT ifnull(message_num,0) as num FROM tel_company where COMPANY='"+company+"'";
		long messageTotalCount = Db.findFirst(totalMessage).getLong("num");
		
		setAttr("total", total);
		setAttr("temp", temp);
		setAttr("assignment", assignment);
		setAttr("accept", accept);
		setAttr("process", process);
		setAttr("finish", finish);
		setAttr("cancel", cancel);
		getSession().setAttribute("messageLeftCount", messageTotalCount);

		render("count.ftl");
	}

	private Date setTime(Date date, int hour, int minute, int second, int ms) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.MINUTE, minute);
		calendar.set(Calendar.SECOND, second);
		calendar.set(Calendar.HOUR_OF_DAY, hour);
		calendar.set(Calendar.MILLISECOND, ms);
		date = calendar.getTime();
		return date;
	}

	public void orderReport() {
		//操作员自己所属品牌
		String company=(String) getSession().getAttribute("company");
		String userRole = (String)getSession().getAttribute("userRole");
		String beginDateStr = this.getPara("beginDate");
		String endDateStr = this.getPara("endDate");
		if(beginDateStr == null || endDateStr == null){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			setAttr("beginDate", sdf.format(Calendar.getInstance().getTime()));
			setAttr("endDate", sdf.format(Calendar.getInstance().getTime()));
			render("order_report.ftl");
			return;
		}

		Date beginDate = TimeUtil.parse(beginDateStr, "yyyy-MM-dd", new Date());
		Date endDate = TimeUtil.parse(endDateStr, "yyyy-MM-dd", new Date());
		beginDate = setTime(beginDate, 0, 0, 0, 0);
		endDate = setTime(endDate, 23, 59, 59, 999);

		String limitSql = " and o.create_time >= ? and o.create_time < ?";
		String sqlTotal = 
				"SELECT company,companyname, "+
				"(SELECT COUNT(*) FROM sys_user s WHERE s.company=c.company) sys_user_num, "+
				"(SELECT COUNT(*) FROM b_user b WHERE b.license_num=c.company) driver_num, "+ //员工数指的代驾员
				"0 member_num, "+
				"0 app_num, "+
				"(SELECT COUNT(*) FROM order_detail o WHERE o.source=c.company AND o.sys_user_id IS NOT NULL AND o.sys_user_id != 1 "+limitSql+") admin_num, "+
				"(SELECT COUNT(*) FROM order_detail o WHERE o.source=c.company AND o.from_source='APP' "+limitSql+") driver_order_num, "+
				"(SELECT COUNT(*) FROM order_detail o WHERE o.source=c.company AND o.sys_user_id=1 "+limitSql+") enterprise_num, "+
				"(SELECT COUNT(*) FROM order_detail o WHERE o.source=c.company "+limitSql+") total_num, "+
				"(SELECT SUM(totalmoney) FROM order_detail o WHERE o.source=c.company "+limitSql+") total_money, "+
				"(SELECT SUM(charges) FROM order_detail o WHERE o.source=c.company "+limitSql+") total_charge, "+
				"(SELECT COUNT(*) FROM order_detail o WHERE o.source=c.company AND o.order_state IN(8,9) "+limitSql+") cancel_num, "+
				"(SELECT COUNT(*) FROM order_detail o WHERE o.source=c.company AND o.ishave_complaint=1 "+limitSql+") complaint_wait_num, "+
				"(SELECT COUNT(*) FROM order_detail o WHERE o.source=c.company AND o.ishave_complaint=2 "+limitSql+") complaint_deal_num, "+
				"(SELECT COUNT(*) FROM tel_company_message m WHERE create_time >DATE_ADD(CURDATE(),INTERVAL -DAY(CURDATE())+1 DAY) AND create_time<LAST_DAY(CURDATE()) AND m.COMPANY=c.company) as message_used_num "+
				"FROM tel_company c where 1=1 ";
		
		if(Constants.ROLE_BRAND_MANAGER.equals(userRole) || Constants.ROLE_MIDDLE_MANAGER.equals(userRole)){
			sqlTotal +=" and c.company='"+company+"' ";
		}
		sqlTotal += " GROUP BY c.company ";
		
		//List<Order> list = Order.dao.find(sqlTotal, beginDate, endDate);
		
		List<Record> list = Db.find(sqlTotal, beginDate, endDate, beginDate, endDate, beginDate, endDate
											, beginDate, endDate, beginDate, endDate, beginDate, endDate
											, beginDate, endDate, beginDate, endDate, beginDate, endDate);
		
		setAttr("beginDate", TimeUtil.format(beginDate, "yyyy-MM-dd"));
		setAttr("endDate", TimeUtil.format(endDate, "yyyy-MM-dd"));
		setAttr("orderList", list);

		render("order_report.ftl");
	}
	
	public void orderDealReport() {
		//操作员自己所属品牌
		String company=(String) getSession().getAttribute("company");
		String userRole = (String)getSession().getAttribute("userRole");
		String beginDateStr = this.getPara("beginDate");
		String endDateStr = this.getPara("endDate");
		if(beginDateStr == null || endDateStr == null){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			setAttr("beginDate", sdf.format(Calendar.getInstance().getTime()));
			setAttr("endDate", sdf.format(Calendar.getInstance().getTime()));
			render("order_deal_report.ftl");
			return;
		}

		Date beginDate = TimeUtil.parse(beginDateStr, "yyyy-MM-dd", new Date());
		Date endDate = TimeUtil.parse(endDateStr, "yyyy-MM-dd", new Date());
		beginDate = setTime(beginDate, 0, 0, 0, 0);
		endDate = setTime(endDate, 23, 59, 59, 999);

		String sqlTotal = 
				" SELECT COUNT(*) totalNum,SUM(totalmoney) as totalmoney,SUM(charges) as charges,source, "+
				" (SELECT c.companyname FROM tel_company c WHERE c.company=source) AS companyname, "+
				" license_num , "+
				" (SELECT c.companyname FROM tel_company c WHERE c.company=license_num) AS drivercompanyname "+
				" FROM order_detail o ,b_user b "+
				" WHERE b.id=o.b_user_id AND order_state=4 "+
				" and o.create_time >= ? and o.create_time < ? ";
				
		
		if(Constants.ROLE_BRAND_MANAGER.equals(userRole) || Constants.ROLE_MIDDLE_MANAGER.equals(userRole)){
			sqlTotal +=" and o.source='"+company+"' ";
		}
		sqlTotal += " GROUP BY o.source,b.license_num ORDER BY source";
		
		List<Record> list = Db.find(sqlTotal, beginDate, endDate);
		
		setAttr("beginDate", TimeUtil.format(beginDate, "yyyy-MM-dd"));
		setAttr("endDate", TimeUtil.format(endDate, "yyyy-MM-dd"));
		setAttr("orderList", list);

		render("order_deal_report.ftl");
	}
	
	public void orderOtherCallReport() {
		//操作员自己所属品牌
		String company=(String) getSession().getAttribute("company");
		String userRole = (String)getSession().getAttribute("userRole");
		String beginDateStr = this.getPara("beginDate");
		String endDateStr = this.getPara("endDate");
		String cellphone = this.getPara("cellphone");
		
		if(beginDateStr == null || endDateStr == null){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			setAttr("beginDate", sdf.format(Calendar.getInstance().getTime()));
			setAttr("endDate", sdf.format(Calendar.getInstance().getTime()));
			render("order_othercall_report.ftl");
			return;
		}

		Date beginDate = TimeUtil.parse(beginDateStr, "yyyy-MM-dd", new Date());
		Date endDate = TimeUtil.parse(endDateStr, "yyyy-MM-dd", new Date());
		beginDate = setTime(beginDate, 0, 0, 0, 0);
		endDate = setTime(endDate, 23, 59, 59, 999);

		String sqlTotal = 
				" SELECT * FROM order_detail o WHERE call_type=2 "+
				" and o.create_time >= ? and o.create_time < ? ";
				
		
		if(Constants.ROLE_BRAND_MANAGER.equals(userRole) || Constants.ROLE_MIDDLE_MANAGER.equals(userRole)){
			sqlTotal +=" and o.source='"+company+"' ";
		}
		if(cellphone != null && !"".equals(cellphone)){
			sqlTotal +=" and o.cell_phone='"+cellphone+"' ";
		}
		sqlTotal +=" order by o.member_id,o.order_state,o.id ";
		
		/*Page<Record> page = Db
				.paginate(
						getParaToInt(0, 1),
						10,
						" SELECT *  ",
						sqlTotal, beginDate, endDate);
		
		setAttr("page", page);*/
		
		List<Record> list = Db.find(sqlTotal, beginDate, endDate);
		
		String companySql = "select * from tel_company";
		List<Record> companyList = Db.find(companySql);
		
		Map<Integer,List> otherCallMap = new HashMap<Integer,List>();
		for(Record record : list){
			int memberId = record.getInt("member_id");
			List itemList = otherCallMap.get(memberId);
			if(itemList == null){
				itemList = new ArrayList();
			}
			for(Record companyItem : companyList){
				String companyCode = companyItem.getStr("company");
				if(companyCode.equals(record.getStr("source"))){
					Integer callProportion = companyItem.getInt("call_proportion");
					if(callProportion == null){
						callProportion = 0;
					}
					BigDecimal charges = (record.getBigDecimal("charges") == null ? new BigDecimal(0):record.getBigDecimal("charges"));
					Double callProportionValue = ( callProportion * charges.doubleValue() )/100;
					record.set("callProportion", callProportionValue);
				}
			}
			itemList.add(record);
			otherCallMap.put(memberId, itemList);
		}
		
		setAttr("beginDate", TimeUtil.format(beginDate, "yyyy-MM-dd"));
		setAttr("endDate", TimeUtil.format(endDate, "yyyy-MM-dd"));
		setAttr("cellphone", cellphone);
		setAttr("otherCallMap", otherCallMap);

		render("order_othercall_report.ftl");
	}

	public void assignmentDriver() {
		int orderId = getParaToInt();
		List<Record> list = Db
				.find("select b.* from order_job a left join b_user b on a.b_user_id = b.id where a.order_id = ?",
						orderId);
		setAttr("list", list);
		render("assignment_driver.ftl");
	}

	public void excelApproval() {
		this.excel("10, 11, 13");
	}

	public void excelNoApproval() {
		this.excel("8, 9, 12");
	}

	private static double getDistance(double lat1, double lng1, double lat2,
			double lng2) {
		double lat = Math.abs(lat1 - lat2);
		double lng = Math.abs(lng1 - lng2);
		double latd = lat * 111.5;
		double lngd = lng * 95.8;
		latd = latd * latd;
		lngd = lngd * lngd;
		double s = Math.sqrt(latd + lngd);
		double ss = (double) (Math.round(s * 10)) / 10;
		return ss;
	}
	
	public void search() {
		String id = getPara("id");
		String mobile = getPara("mobile");
		String company=(String) getSession().getAttribute("company");
		String userRole = (String)getSession().getAttribute("userRole");
		
		String from = "from order_detail a left join driver_member b on a.member_id = b.id left join b_user c on a.b_user_id = c.id  where 1=1 ";
		if (StringUtils.isNotBlank(id)) {
			from += " and a.id = " + id;
		}
		if (StringUtils.isNotBlank(mobile)) {
			from += " and a.cell_phone = '" + mobile +"'";
		}
		from = Constants.appendSqlForRoleCom(from, userRole, company);
		
		from += " order by a.id desc";
		Page<Record> page = Db
				.paginate(
						getParaToInt(0, 1),
						10,
						"select a.*,b.real_name as real_name2,b.user_name,b.cell_phone as cell_phone2,b.sex as sex2 ,b.plage_number as plage_number2,c.name as driver_name , c.job_number,c.phone as driver_phone ",
						from);
		setAttr("page", page);
		
		List<Record> rs = page.getList();
		if(rs != null && rs.size() != 0) {
			Record r = rs.get(0);
			Long order_state = r.getLong("order_state");
			int ishave_complaint = 0;
			if(r.get("ishave_complaint") != null) {
				ishave_complaint = r.getInt("ishave_complaint");
			}
			if(order_state == 0) {
				render("accept_list.ftl");
			} else  if(order_state == 1) {
				render("accepted_list.ftl");
			}else  if(order_state == 2) {
				render("arrived_list.ftl");
			}else  if(order_state == 3) {
				render("process_list.ftl");
			}else  if(order_state == 4 && ishave_complaint != 1 && ishave_complaint != 2) {
				render("finish_list.ftl");
			}else  if(order_state == 6) {
				render("assignment_list.ftl");
			}else  if(order_state == 8 || order_state == 9 || order_state == 12) {
				render("noApprovalList.ftl");
			}else  if(order_state == 10 || order_state == 11 || order_state == 13) {
				render("approvalList.ftl");
			}else  if(ishave_complaint == 1) {
				render("complaint_list.ftl");
			}else  if(ishave_complaint == 2) {
				render("complaint_approval_list.ftl");
			}
		} else {
			render("error.ftl");
		}
		
	}
	
	public void addTempMember()
	{
		Member member = null;
		int memberId = getParaToInt();
		if (memberId == 0) {
			member = getModel(Member.class);
		}
		
		setAttr("member", member);
	    renderJson();
	}
	
	/**(order_add3 页面上的员工抢单按钮，调用这个逻辑)
	 * 关于订单的生成之后的逻缉：订单生成之后，第一时间推送给周围指定公里内的自家公司司机APP上面，
	 * 如果超过30秒自己品牌下的司机没有人接订单，
	 * 这时推送给同等范围内其它品牌的司机APP上面，
	 * 超过1分钟如果订单还没有人接，这时订单才会在待分派订单中显示，
	 * 这时客服工作人员才会进行人工派单。
	 */
	public void save3() {
		String orderCategoryType = getPara("orderCategoryType");
		String clientPhone = getPara("clientPhone");
		String clientName = getPara("clientName");
		Integer driverKm = getParaToInt("driverKm");
		Integer driverMoney = getParaToInt("driverMoney");
		String fromSource = getPara("fromSource");
		String fromSourceValue = getPara("fromSourceValue");
		Integer driverRateKm = getParaToInt("driverRateKm");
		String couponPass = getPara("couponPass");
		String memo = getPara("memo");
		Integer driverNum = getParaToInt("driverNum");
		Integer weight = getParaToInt("weight");
		
		int orderNum = 1;
		if(driverNum != null){
			orderNum = driverNum.intValue();
		}
		String city = getPara("city");
		Integer cityId = getParaToInt("city_id");
		if(cityId != null){
			City city1 = City.dao.findById(cityId);
			if(city1 != null){
				city = city1.getStr("city_name");
			}
		}
		//String province = getPara("province");
		String endpoint = getPara("endpoint");
		String card_no = getPara("card_no");
		String engine_no = getPara("engine_no");
		String receiveName = getPara("receiveName");
		String receivePhone = getPara("receivePhone");
		String pointTime = getPara("pointTime");
		String clean_area = getPara("clean_area");
		String wish_finish_time = getPara("wish_finish_time");
		String trunk_type = getPara("trunk_type");
		String goods_type = getPara("goods_type");
		String goods_order = getPara("goods_order");
		String send_no = getPara("send_no");
		String education_type = getPara("educationType");
		String position_type = getPara("positionType");
		String cur_station = getPara("curStation");
		String cur_year_salary = getPara("curYearSalary");
		String wish_station = getPara("wishStation");
		String wish_year_salary = getPara("wishYearSalary");
		String cur_station_status = getPara("jobStatusType");
		String sex = getPara("sex");
		log.info("clientPhone:" + clientPhone + ",clientName:" + clientName + ",driverKm:" + driverKm
						  +",receiveName:"+receiveName+",receivePhone:"+receivePhone+",pointTime:"+pointTime
						  +",city:"+city+",card_no:"+card_no+",engine_no:"+engine_no
						  +",clean_area:"+clean_area+",wish_finish_time:"+wish_finish_time
						  +",trunk_type:"+trunk_type+",goods_type:"+goods_type
						  +",goods_order:"+goods_order+",education_type:"+education_type
						  +",position_type:"+position_type+",cur_station:"+cur_station
						  +",cur_year_salary:"+cur_year_salary+",wish_station:"+wish_station
						  +",wish_year_salary:"+wish_year_salary+",cur_station_status:"+cur_station_status
						  +",sex:"+sex);
		
		
		Date d = new Date();
		
		List<Integer> orderIds = new ArrayList<Integer>();
		if(TypeConstant.OrderType.DRIVER.name().equals(orderCategoryType)){
			Order order = (Order)getModel(Order.class);
			order.put("sys_user_id", getSession().getAttribute("userId"));
			order.put("create_time", d);
			order.put("publish_time", d);
			order.put("order_state", Integer.valueOf(0));
			order.put("city", city);
			order.put("endpoint", endpoint);
			//order.put("order_state", Integer.valueOf(6));
			order.put("cell_phone", clientPhone);
			order.put("real_name", clientName);
			order.put("kilometre", Integer.valueOf(driverKm));
			order.put("totalmoney", Integer.valueOf(driverMoney));
			order.put("source",fromSourceValue);
			order.put("remark", memo);
			order.put("order_category_type", orderCategoryType);
			order.put("auto_status", 1); //自动派单
			order.put("point_time", pointTime);
			order.put("from_source", TypeConstant.OrderFromSource.GRAB.name());
			for (int i = 0; i < orderNum; ++i) {
				order.remove("id");
				order.save();
				
				orderIds.add(order.getInt("id"));
			}
		}else if(TypeConstant.OrderType.DELIVERY.name().equals(orderCategoryType)
				|| TypeConstant.OrderType.UNLOCK.name().equals(orderCategoryType)
				|| TypeConstant.OrderType.PARK.name().equals(orderCategoryType)){
			Order order = (Order)getModel(Order.class);
			
			order.put("sys_user_id", getSession().getAttribute("userId"));
			order.put("create_time", d);
			//order.put("order_state", Integer.valueOf(0));
			order.put("city", city);
			order.put("card_no", card_no);
			order.put("engine_no", engine_no);
			order.put("endpoint", endpoint);
			order.put("order_state", Integer.valueOf(6));
			order.put("kilometre", driverKm);
			order.put("totalmoney", driverMoney);
			order.put("cell_phone", clientPhone);
			order.put("real_name", clientName);
			order.put("receive_name", receiveName);
			order.put("receive_phone", receivePhone);
			order.put("point_time", pointTime);
			order.put("source",fromSourceValue);
			order.put("remark", memo);
			order.put("clean_area", clean_area);
			order.put("wish_finish_time", wish_finish_time);
			order.put("trunk_type", trunk_type);
			order.put("goods_type", goods_type);
			order.put("goods_order", goods_order);
			order.put("send_no", send_no);
			order.put("education_type", education_type);
			order.put("position_type", position_type);
			order.put("cur_station", cur_station);
			order.put("cur_year_salary", cur_year_salary);
			order.put("wish_station", wish_station);
			order.put("wish_year_salary", wish_year_salary);
			order.put("cur_station_status", cur_station_status);
			order.put("sex", sex);
			order.put("plage_number", orderNum);
			order.put("weight", weight);
			
			order.put("order_category_type", orderCategoryType);
			order.put("auto_status", 1);  //自动派单
			order.put("from_source", TypeConstant.OrderFromSource.GRAB.name());
			order.put("city_id", cityId);
			
			if(TypeConstant.OrderType.DELIVERY.name().equals(orderCategoryType)){
				
				order.put("kilometre", driverKm);
				order.put("totalmoney", driverMoney);
			}
			for (int i = 0; i < orderNum; ++i) {
				order.remove("id");
				order.save();
				orderIds.add(order.getInt("id"));
			}
		}
		//SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//String abcValue = sdf.format(d);
		System.out.println("orderIds:"+orderIds);
		if(orderIds.size() > 0){
			for(Integer orderId : orderIds){
				String sql = "select id,startpoint_latitude,startpoint_longitude,startpoint,endpoint from order_detail where id=?";
				Record rec = Db.findFirst(sql,orderId);
				//int orderid = rec.getInt("id").intValue();
				double latd = rec.getBigDecimal("startpoint_latitude").doubleValue();
				double longd = rec.getBigDecimal("startpoint_longitude").doubleValue();
				String strStartpoint = rec.getStr("startpoint");
				String strEndpoint = rec.getStr("endpoint");
				//指派给本公司代驾员
				String company=(String) getSession().getAttribute("company");
				myAssignment(orderId, latd, longd, driverRateKm, strStartpoint, strEndpoint, company);
			}
		}

	    
	    //指派给本公司的代驾员
	    //myAssignment(orderIds.get(0), order, longd, driverRateKm, str, endpoint, "SH");
	    redirect("/order/assignmentList");
	}
	
	/*TypeConstant.OrderType.DELIVERY.name().equals(orderCategoryType)
	|| TypeConstant.OrderType.CAROVERHAUL.name().equals(orderCategoryType)
	|| TypeConstant.OrderType.AIRPORT.name().equals(orderCategoryType)
	|| TypeConstant.OrderType.STATION.name().equals(orderCategoryType)
	|| TypeConstant.OrderType.UNLOCK.name().equals(orderCategoryType)
	|| TypeConstant.OrderType.BREAKRULE.name().equals(orderCategoryType)
	|| TypeConstant.OrderType.CLEANSERVER.name().equals(orderCategoryType)
	|| TypeConstant.OrderType.TRUNK.name().equals(orderCategoryType)
	|| TypeConstant.OrderType.HEADHUNTING.name().equals(orderCategoryType)*/
	//人工派单
	public void save4() {
		String orderCategoryType = getPara("orderCategoryType");
		String clientPhone = getPara("clientPhone");
		String clientName = getPara("clientName");
		Integer driverKm = getParaToInt("driverKm");
		Integer driverMoney = getParaToInt("driverMoney");
		String company=(String) getSession().getAttribute("company");
		String fromSource = getPara("fromSource");
		String fromSourceValue = company;//getPara("fromSourceValue");
		Integer driverRateKm = getParaToInt("driverRateKm");
		String couponPass = getPara("couponPass");
		String memo = getPara("memo");
		Integer driverNum = getParaToInt("driverNum");
		int orderNum = 1;
		if(driverNum != null){
			orderNum = driverNum.intValue();
		}
		Integer number=getParaToInt("number");//选择的司机数量
		if(number!=null){
			if(number>orderNum)
				orderNum=number;
		}
		String city = getPara("city");
		//String province = getPara("province");
		String endpoint = getPara("endpoint");
		String card_no = getPara("card_no");
		String engine_no = getPara("engine_no");
		String receiveName = getPara("receiveName");
		String receivePhone = getPara("receivePhone");
		String pointTime = getPara("pointTime");
		String clean_area = getPara("clean_area");
		String wish_finish_time = getPara("wish_finish_time");
		String trunk_type = getPara("trunk_type");
		String goods_type = getPara("goods_type");
		String goods_order = getPara("goods_order");
		String send_no = getPara("send_no");
		String education_type = getPara("educationType");
		String position_type = getPara("positionType");
		String cur_station = getPara("curStation");
		String cur_year_salary = getPara("curYearSalary");
		String wish_station = getPara("wishStation");
		String wish_year_salary = getPara("wishYearSalary");
		String cur_station_status = getPara("jobStatusType");
		String sex = getPara("sex");
		String weight = getPara("weight");
		
		Integer cityId = getParaToInt("city_id");
		if(cityId != null){
			City city1 = City.dao.findById(cityId);
			if(city1 != null){
				city = city1.getStr("city_name");
			}
		}
		Integer terminal_id = getParaToInt("terminal_id");
		if(terminal_id != null){
			Terminal terminal = Terminal.dao.findById(terminal_id);
			if(TypeConstant.OrderType.PARK.name().equals(orderCategoryType)){
				wish_station = terminal.getStr("terminal_name");
			}
		}
		List<Integer> orderIds = new ArrayList<Integer>();
		log.info("clientPhone:" + clientPhone + ",clientName:" + clientName + ",driverKm:" + driverKm
						  +",receiveName:"+receiveName+",receivePhone:"+receivePhone+",pointTime:"+pointTime
						  +",city:"+city+",card_no:"+card_no+",engine_no:"+engine_no
						  +",clean_area:"+clean_area+",wish_finish_time:"+wish_finish_time
						  +",trunk_type:"+trunk_type+",goods_type:"+goods_type
						  +",goods_order:"+goods_order+",education_type:"+education_type
						  +",position_type:"+position_type+",cur_station:"+cur_station
						  +",cur_year_salary:"+cur_year_salary+",wish_station:"+wish_station
						  +",wish_year_salary:"+wish_year_salary+",cur_station_status:"+cur_station_status
						  +",sex:"+sex);
		
		Date d = new Date();
		Order order = (Order)getModel(Order.class);
		if(TypeConstant.OrderType.DRIVER.name().equals(orderCategoryType)){
			order.put("sys_user_id", getSession().getAttribute("userId"));
			order.put("create_time", d);
			order.put("order_state", Integer.valueOf(0));
			order.put("city", city);
			order.put("endpoint", endpoint);
			order.put("order_state", Integer.valueOf(6));
			order.put("cell_phone", clientPhone);
			order.put("real_name", clientName);
			order.put("kilometre", Integer.valueOf(driverKm));
			order.put("totalmoney", Integer.valueOf(driverMoney));
			order.put("source",fromSourceValue);
			order.put("remark", memo);
			order.put("order_category_type", orderCategoryType);
			order.put("point_time", pointTime);
			order.put("auto_status", 2); //强制派单
			order.put("from_source", TypeConstant.OrderFromSource.GRAB.name());
			for (int i = 0; i < orderNum; ++i) {
				order.remove("id");
				order.save();
				
				orderIds.add(order.getInt("id"));
			}
		}else if(TypeConstant.OrderType.DELIVERY.name().equals(orderCategoryType)
				|| TypeConstant.OrderType.UNLOCK.name().equals(orderCategoryType)
				|| TypeConstant.OrderType.PARK.name().equals(orderCategoryType)){
			order.put("sys_user_id", getSession().getAttribute("userId"));
			order.put("create_time", d);
			order.put("order_state", Integer.valueOf(0));
			order.put("city", city);
			order.put("card_no", card_no);
			order.put("engine_no", engine_no);
			order.put("endpoint", endpoint);
			order.put("order_state", Integer.valueOf(6));
			order.put("kilometre", driverKm);
			order.put("totalmoney", driverMoney);
			order.put("cell_phone", clientPhone);
			order.put("real_name", clientName);
			order.put("receive_name", receiveName);
			order.put("receive_phone", receivePhone);
			order.put("point_time", pointTime);
			order.put("source",fromSourceValue);
			order.put("remark", memo);
			order.put("clean_area", clean_area);
			order.put("wish_finish_time", wish_finish_time);
			order.put("trunk_type", trunk_type);
			order.put("goods_type", goods_type);
			order.put("goods_order", goods_order);
			order.put("send_no", send_no);
			order.put("education_type", education_type);
			order.put("position_type", position_type);
			order.put("cur_station", cur_station);
			order.put("cur_year_salary", cur_year_salary);
			order.put("wish_station", wish_station);
			order.put("wish_year_salary", wish_year_salary);
			order.put("cur_station_status", cur_station_status);
			order.put("sex", sex);
			order.put("plage_number", orderNum);
			order.put("auto_status", 2); //强制派单
			order.put("order_category_type", orderCategoryType);
			order.put("city_id", cityId);
			order.put("weight", weight);
			order.put("from_source", TypeConstant.OrderFromSource.GRAB.name());
			//order.remove("id");
			
			if(TypeConstant.OrderType.DELIVERY.name().equals(orderCategoryType)){
				
				order.put("kilometre", driverKm);
				order.put("totalmoney", driverMoney);
			}
			for (int i = 0; i < orderNum; ++i) {
				order.remove("id");
				order.save();
				
				orderIds.add(order.getInt("id"));
			}
		}
		
	    int id = order.get("id");
	    setAttr("id",StringUtils.join(orderIds.toArray(),";"));
	    if(TypeConstant.OrderType.DRIVER.name().equals(orderCategoryType))
	        renderJson();
	    else
	        redirect("/order/assignment/"+id);
	}
	
	public void save5() {
		String orderCategoryType = getPara("orderCategoryType");
		String clientPhone = getPara("clientPhone");
		String clientName = getPara("clientName");
		Integer driverKm = getParaToInt("driverKm");
		Integer driverMoney = getParaToInt("driverMoney");
		String city = getPara("city");
		String card_no = getPara("card_no");
		String engine_no = getPara("engine_no");
		String fromSource = getPara("fromSource");
		String fromSourceValue = getPara("fromSourceValue");
		Integer driverRateKm = getParaToInt("driverRateKm");
		String couponPass = getPara("couponPass");
		String memo = getPara("memo");
		Integer driverNum = getParaToInt("driverNum");
		int orderNum = 1;
		if(driverNum != null){
			orderNum = driverNum.intValue();
		}
		Integer cityId = getParaToInt("city_id");
		if(cityId != null){
			City city1 = City.dao.findById(cityId);
			if(city1 != null){
				city = city1.getStr("city_name");
			}
		}
		String endpoint = getPara("endpoint");
		String receiveName = getPara("receiveName");
		String receivePhone = getPara("receivePhone");
		String pointTime = getPara("pointTime");
		String clean_area = getPara("clean_area");
		String wish_finish_time = getPara("wish_finish_time");
		String trunk_type = getPara("trunk_type");
		String goods_type = getPara("goods_type");
		String goods_order = getPara("goods_order");
		String send_no = getPara("send_no");
		String education_type = getPara("educationType");
		String position_type = getPara("positionType");
		String cur_station = getPara("curStation");
		String cur_year_salary = getPara("curYearSalary");
		String wish_station = getPara("wishStation");
		String wish_year_salary = getPara("wishYearSalary");
		String cur_station_status = getPara("jobStatusType");
		String sex = getPara("sex");
		String weight = getPara("weight");
		log.info("clientPhone:" + clientPhone + ",clientName:" + clientName + ",driverKm:" + driverKm
						  +",receiveName:"+receiveName+",receivePhone:"+receivePhone+",pointTime:"+pointTime
						  +",city:"+city+",card_no:"+card_no+",engine_no:"+engine_no
						  +",clean_area:"+clean_area+",wish_finish_time:"+wish_finish_time
						  +",trunk_type:"+trunk_type+",goods_type:"+goods_type
						  +",goods_order:"+goods_order+",education_type:"+education_type
						  +",position_type:"+position_type+",cur_station:"+cur_station
						  +",cur_year_salary:"+cur_year_salary+",wish_station:"+wish_station
						  +",wish_year_salary:"+wish_year_salary+",cur_station_status:"+cur_station_status
						  +",sex:"+sex);
		
		Date d = new Date();
		Order order = (Order)getModel(Order.class);
		if(TypeConstant.OrderType.DRIVER.name().equals(orderCategoryType)){
			order.put("sys_user_id", getSession().getAttribute("userId"));
			order.put("create_time", d);
			order.put("order_state", Integer.valueOf(0));
			order.put("city", city);
			order.put("endpoint", endpoint);
			order.put("order_state", Integer.valueOf(6));
			order.put("cell_phone", clientPhone);
			order.put("real_name", clientName);
			order.put("kilometre", Integer.valueOf(driverKm));
			order.put("totalmoney", Integer.valueOf(driverMoney));
			order.put("source",fromSourceValue);
			order.put("remark", memo);
			order.put("order_category_type", orderCategoryType);
			order.put("point_time", pointTime);
			order.put("auto_status", 3);//自动保存
			order.put("from_source", TypeConstant.OrderFromSource.GRAB.name());
			order.remove("id");
			order.save();
		}else if(TypeConstant.OrderType.DELIVERY.name().equals(orderCategoryType)
				|| TypeConstant.OrderType.UNLOCK.name().equals(orderCategoryType)
				|| TypeConstant.OrderType.PARK.name().equals(orderCategoryType)){
			order.put("sys_user_id", getSession().getAttribute("userId"));
			order.put("create_time", d);
			order.put("order_state", Integer.valueOf(0));
			order.put("city", city);
			order.put("card_no", card_no);
			order.put("engine_no", engine_no);
			order.put("endpoint", endpoint);
			order.put("order_state", Integer.valueOf(6));
			order.put("kilometre", driverKm);
			order.put("totalmoney", driverMoney);
			order.put("cell_phone", clientPhone);
			order.put("real_name", clientName);
			order.put("receive_name", receiveName);
			order.put("receive_phone", receivePhone);
			order.put("point_time", pointTime);
			order.put("source",fromSourceValue);
			order.put("remark", memo);
			order.put("clean_area", clean_area);
			order.put("wish_finish_time", wish_finish_time);
			order.put("trunk_type", trunk_type);
			order.put("goods_type", goods_type);
			order.put("goods_order", goods_order);
			order.put("send_no", send_no);
			order.put("education_type", education_type);
			order.put("position_type", position_type);
			order.put("cur_station", cur_station);
			order.put("cur_year_salary", cur_year_salary);
			order.put("wish_station", wish_station);
			order.put("wish_year_salary", wish_year_salary);
			order.put("cur_station_status", cur_station_status);
			order.put("sex", sex);
			order.put("auto_status", 3);//自动保存
			order.put("plage_number", orderNum);
			order.put("order_category_type", orderCategoryType);
			order.put("city_id", cityId);
			order.put("weight", weight);
			order.put("from_source", TypeConstant.OrderFromSource.GRAB.name());
			
			order.remove("id");
			
			if(TypeConstant.OrderType.DELIVERY.name().equals(orderCategoryType)){
				
				order.put("kilometre", driverKm);
				order.put("totalmoney", driverMoney);
			}
			order.save();
		}
		
	    redirect("/order/assignmentList");
	}
	
	private void myAssignment(int orderid,double latd,double longd,double dis,String startPost,String areaPost,String whereStr)
	{
		log.info("myAssignment 本身品牌司机  ");
		//自动派单 本身品牌
		//判断方圆10公里有无代驾员, 无更新状态6， 有更新0
		HashMap<Integer, String> driverPhoneMap = new HashMap<Integer, String>();
		//String sql = "select id, phone, latitude, longitude from b_user where latitude is not null and longitude is not null and canuse=1 and status = 0 and job_number like '" + whereStr + "%'";
		String sql = "select id, phone, latitude, longitude, device_id from b_user where latitude is not null and longitude is not null and canuse=1 and status = 0 and license_num = '" + whereStr + "'";
		List<Record> recList=Db.find(sql);
		for(Record rec:recList) {
			double distance = getDistance(latd, longd,rec.getBigDecimal("latitude").floatValue() ,rec.getBigDecimal("longitude").floatValue() );
			//计算是否超过10公里
			if(distance < dis) {
				driverPhoneMap.put(rec.getInt("id"), rec.getStr("device_id"));
			}
		}

		String updateOrderSql = "update order_detail set order_state = 0 where id = " + orderid;
		
		if(!driverPhoneMap.isEmpty()) {
			log.info("myAssignment 订单："+orderid+",10公里范围内有司机，司机：" + driverPhoneMap);
			int i=driverPhoneMap.size();
			int j=4;
			Object[][] paras = new Object[i][j];
			int k=0;
			for (Integer driverId : driverPhoneMap.keySet()) {
				log.info("SubmiOrderServlet 订单："+orderid+",driverId：" + driverId);
				paras[k][0]=orderid;
				paras[k][1]=driverId;
				paras[k][2]=new Timestamp(System.currentTimeMillis());
				paras[k][3]=0;
				k++; 
			} 
			Db.batch("insert into order_job(order_id , b_user_id , job_time ,status) values ( ? , ? , ? , ?)", paras);
			log.info("myAssignment 订单："+orderid+",分派成功");
			Order order = Order.dao.findById(orderid);
			for (Integer driverId : driverPhoneMap.keySet()) {
					String content ="";
				    if("DRIVER".equals(order.getStr("order_category_type")) || "DELIVERY".equals(order.getStr("order_category_type")))
				    	content= "出发地：" + startPost + "，目标方向："
							+ areaPost + "，快去接收吧！";
				    else if("UNLOCK".equals(order.getStr("order_category_type"))){
				    	content= "服务地点：" + startPost + "，快去接收吧！";
				    }
				    else if("PARK".equals(order.getStr("order_category_type"))){
				    	content= "接车地点：" + startPost + "，快去接收吧！";
				    }
				    else{
				    	content= "出发地：" + startPost + "，目标方向："
								+ areaPost + "，快去接收吧！";
				    }
					log.info("SubmiOrderServlet 订单："+orderid+",driverId：" + driverId+",content:"+content);
					
					String deviceId = driverPhoneMap.get(driverId);
					log.info("deviceId:" + deviceId);
					if(!StringUtils.isEmpty(deviceId)){
						Map<String, String> paramsMap = new HashMap<String, String>();
						paramsMap.put("orderId", orderid+"");
						paramsMap.put("kilometre", order.getStr("kilometer"));
		                paramsMap.put("from_source", order.getStr("from_source"));
		                if(order.getBigDecimal("startpoint_latitude")==null)
		                    paramsMap.put("startpoint_latitude", "0");
		                else
		                    paramsMap.put("startpoint_latitude", order.getBigDecimal("startpoint_latitude").toString());
		                if(order.getTimestamp("create_time")==null)
		                    paramsMap.put("create_time", "");
		                else
		                    paramsMap.put("create_time", order.getTimestamp("create_time").toString());
		                paramsMap.put("pay_type", order.getInt("pay_type").toString());
		                paramsMap.put("order_type", order.getInt("order_type").toString());
		                paramsMap.put("totalmoney", order.getBigDecimal("totalmoney").toString());
		                paramsMap.put("source", order.getStr("source"));
		                paramsMap.put("driver_got", order.getBigDecimal("driver_got").toString());
		                paramsMap.put("startpoint", order.getStr("startpoint"));
		                if(order.getTimestamp("publish_time")==null)
		                    paramsMap.put("publish_time","");
		                else
		                    paramsMap.put("publish_time",order.getTimestamp("publish_time").toString());
		                paramsMap.put("cityId", "");
		                if(order.getLong("order_state")==null)
		                    paramsMap.put("order_state", "0");
		                else
		                    paramsMap.put("order_state", order.getLong("order_state").toString());
		                if(order.getTimestamp("point_time")==null){
		                    paramsMap.put("point_time", "");
		                    paramsMap.put("reFlag", "0");
		                }
		                else{
		                    paramsMap.put("point_time", order.getTimestamp("point_time").toString());
		                    if(TimeUtil.compareTime(order.getTimestamp("point_time").toString()))
		                        paramsMap.put("reFlag", "1");
		                    else{
		                        paramsMap.put("reFlag", "0");
		                    }
		                }
		                paramsMap.put("endpoint", order.getStr("endpoint"));
		                paramsMap.put("startpoint_longitude", order.getBigDecimal("startpoint_longitude").toString());
		                if(order.getBigDecimal("charges")==null)
		                    paramsMap.put("charges", "0");
		                else
		                    paramsMap.put("charges", order.getBigDecimal("charges").toString());
		                paramsMap.put("t", "order:"+ order.getStr("order_category_type").toLowerCase()+":accept");
		                paramsMap.put("member_id", order.getInt("member_id").toString());
		                paramsMap.put("b_user_id", order.getInt("b_user_id").toString());
		                paramsMap.put("order_category_type", order.getStr("order_category_type"));
						try {
							PushTokenUtils.sendPush(content, deviceId, JpushType.order_driver_accept, paramsMap);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					//SmsUtil.sendMessage(driverPhoneMap.get(driverId), content);
			}
			updateOrderSql = "update order_detail set order_state = 0 ,publish_time = now() where id = " + orderid;
			
			log.info("myAssignment  "+dis+"公里范围内有"+i+"位司机有空");
			
			//加入对该订单的后续查看线程(延时2)
			OrderRunnable m1=new OrderRunnable(""+orderid,orderid,dis,whereStr,OrderRunnable.GRAB_MODE,2,"");
			Thread t1=new Thread(m1);
			t1.start();
			
		} else {
			log.info("SubmiOrderServlet 10公里范围内没有司机");
			System.out.println("myAssignment  "+dis+"公里范围内没有司机，或司机都在忙");
			//直接发其它品牌的司机
			myAssignment2(orderid,dis,whereStr,false,3,OrderRunnable.GRAB_MODE);
		}
		log.info("myAssignment updateOrderSql:"+updateOrderSql);
		Db.update(updateOrderSql);
		
	}

	//10公里范围内没有本公司司机的派单逻辑
	//在OrderRunnable里面运行
	//same 是否 同公司派单
	public static void myAssignment2(int orderId,double dis,String whereStr,boolean same,int times,String mode)
	{
		log.info("myAssignment2 其它品牌司机  ");
		String sql0 = "select id,startpoint_latitude,startpoint_longitude,startpoint,endpoint,order_state from order_detail where id="+orderId;
		Record rec0=Db.findFirst(sql0);
		long order_state=rec0.getLong("order_state");
		if(order_state==0 || order_state==6){
			int orderid=rec0.getInt("id");
			double latd=rec0.getBigDecimal("startpoint_latitude").doubleValue();
			double longd=rec0.getBigDecimal("startpoint_longitude").doubleValue();
			String startPost=rec0.getStr("startpoint");
			String areaPost=rec0.getStr("endpoint");
			
			//自动派单 其它品牌
			//判断方圆10公里有无代驾员, 无更新状态6， 有更新0
			HashMap<Integer, String> driverPhoneMap = new HashMap<Integer, String>();
			//String sql = "select id, phone, latitude, longitude from b_user where latitude is not null and longitude is not null and canuse=1 and status = 0 and job_number not like '" + whereStr + "%'";
			String sql ="";
			if(same){
				sql= "select id, phone, latitude, longitude,device_id from b_user where latitude is not null and longitude is not null and canuse=1 and status = 0 and license_num = '" + whereStr + "'";
			}else{
				sql= "select id, phone, latitude, longitude,device_id from b_user where latitude is not null and longitude is not null and canuse=1 and status = 0 and license_num <> '" + whereStr + "'";
			}
			List<Record> recList=Db.find(sql);
			for(Record rec:recList) {
				double distance = getDistance(latd, longd,rec.getBigDecimal("latitude").floatValue() ,rec.getBigDecimal("longitude").floatValue() );
				//计算是否超过10公里
				if(distance < dis) {
					driverPhoneMap.put(rec.getInt("id"), rec.getStr("device_id"));
				}
			}
			
			log.info("myAssignment2  driverPhoneMap:"+driverPhoneMap);

			String updateOrderSql = "update order_detail set order_state = 0 where id = " + orderid;
			if(!driverPhoneMap.isEmpty()) {
				//log.debug("SubmiOrderServlet 订单："+orderid+",10公里范围内有司机，司机：" + driverPhoneMap);
				int i=driverPhoneMap.size();
				int j=4;
				Object[][] paras = new Object[i][j];
				int k=0;
				for (Integer driverId : driverPhoneMap.keySet()) {
					//log.debug("SubmiOrderServlet 订单："+orderid+",driverId：" + driverId);
					paras[k][0]=orderid;
					paras[k][1]=driverId;
					paras[k][2]=new Timestamp(System.currentTimeMillis());
					paras[k][3]=0;
					k++;
				}
				Db.batch("insert into order_job(order_id , b_user_id , job_time ,status) values ( ? , ? , ? , ?)", paras);
				Order order=Order.dao.findById(orderid);
				//log.debug("SubmiOrderServlet 订单："+orderid+",分派成功");
				for (Integer driverId : driverPhoneMap.keySet()) {
						String content = "出发地：" + startPost + "，目标方向："
								+ areaPost + "，快去接收吧！";
						//log.debug("SubmiOrderServlet 订单："+orderid+",driverId：" + driverId+",content:"+content);
						//SmsUtil.sendMessage(driverPhoneMap.get(driverId), content);
						String deviceId = driverPhoneMap.get(driverId);
						log.debug("deviceId:" + deviceId);
						if(!StringUtils.isEmpty(deviceId)){
							Map<String, String> paramsMap = new HashMap<String, String>();
							paramsMap.put("orderId", orderid+"");
			                paramsMap.put("kilometre", order.getStr("kilometer"));
			                paramsMap.put("from_source", order.getStr("from_source"));
			                if(order.getBigDecimal("startpoint_latitude")==null)
			                    paramsMap.put("startpoint_latitude", "0");
			                else
			                    paramsMap.put("startpoint_latitude", order.getBigDecimal("startpoint_latitude").toString());
			                if(order.getTimestamp("create_time")==null)
			                    paramsMap.put("create_time", "");
			                else
			                    paramsMap.put("create_time", order.getTimestamp("create_time").toString());
			                paramsMap.put("pay_type", order.getInt("pay_type").toString());
			                paramsMap.put("order_type", order.getInt("order_type").toString());
			                paramsMap.put("totalmoney", order.getBigDecimal("totalmoney").toString());
			                paramsMap.put("source", order.getStr("source"));
			                paramsMap.put("driver_got", order.getBigDecimal("driver_got").toString());
			                paramsMap.put("startpoint", order.getStr("startpoint"));
			                if(order.getTimestamp("publish_time")==null)
			                    paramsMap.put("publish_time","");
			                else
			                    paramsMap.put("publish_time",order.getTimestamp("publish_time").toString());
			                paramsMap.put("reFlag", "0");
			                paramsMap.put("cityId", "");
			                if(order.getLong("order_state")==null)
			                    paramsMap.put("order_state", "0");
			                else
			                    paramsMap.put("order_state", order.getLong("order_state").toString());
			                if(order.getTimestamp("point_time")==null)
			                    paramsMap.put("point_time", "");
			                else
			                    paramsMap.put("point_time", order.getTimestamp("point_time").toString());
			                paramsMap.put("endpoint", order.getStr("endpoint"));
			                paramsMap.put("startpoint_longitude", order.getBigDecimal("startpoint_longitude").toString());
			                if(order.getBigDecimal("charges")==null)
			                    paramsMap.put("charges", "0");
			                else
			                    paramsMap.put("charges", order.getBigDecimal("charges").toString());
			                paramsMap.put("t", "order:"+ order.getStr("order_category_type").toLowerCase()+":accept");
			                paramsMap.put("member_id", order.getInt("member_id").toString());
			                paramsMap.put("b_user_id", order.getInt("b_user_id").toString());
			                paramsMap.put("order_category_type", order.getStr("order_category_type"));
							try {
								PushTokenUtils.sendPush(content, deviceId, JpushType.order_driver_accept, paramsMap);
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
				}
				updateOrderSql = "update order_detail set order_state = 0 ,publish_time = now() where id = " + orderid;
				Db.update(updateOrderSql);
				log.info("myAssignment2  updateOrderSql:"+updateOrderSql);
				log.info("myAssignment  "+dis+"公里范围内有"+i+"位司机有空");
				
				//加入对该订单的后续查看线程(延时3)
				OrderRunnable m1=new OrderRunnable(""+orderid,orderid,dis,whereStr,mode,times+1,"");
				Thread t1=new Thread(m1);
				t1.start();
			} else {
				//log.debug("SubmiOrderServlet 10公里范围内没有司机");
				log.info("myAssignment3 "+dis+"公里范围内没有司机，或司机都在忙");
				
				myAssignment3(orderId);
			}
		}
	}

	//10公里范围内既没有本公司司机也没有其他公司的司机，订单状态改为人工派单
	//在OrderRunnable里面运行
	public static void myAssignment3(int orderId){
		//5分钟后改为自动改手工分单
		String sql0 = "select order_state from order_detail where id="+orderId;
		Record rec0=Db.findFirst(sql0);
		long order_state=rec0.getLong("order_state");
		if(order_state==0){
			String updateOrderSql = "update order_detail set order_state = 6 where id = " + orderId;
			Db.update(updateOrderSql);
			log.info("myAssignment3 updateOrderSql:"+updateOrderSql);
		}
	}
	
	public void telCall()
	{
		//String telCallNumb = getAttr("telNumber");
		//String telSelfNumb = getAttr("telNumberSelf");
		String telCallNumb = getPara("telNumber");
	    String telSelfNumb = getPara("telNumberSelf");

	    Date date = new Date();
	    DateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");
	    DateFormat formatTime = new SimpleDateFormat("HH:mm");
	    String varDate = formatDate.format(date);
	    String varTime = formatTime.format(date);

	    setAttr("varDate", varDate);
	    setAttr("varTime", varTime);
	    setAttr("telCallNumb", telCallNumb);
	    setAttr("telSelfNumb", telSelfNumb);
	    
	    Record rec = Db.findFirst("select companyname,company FROM tel_company where tel = '"+telSelfNumb+"'");
	    if(rec != null){
	    	String orderCompany= rec.getStr("company");
	    	String orderCompanyName= rec.getStr("companyname");
	    	setAttr("orderCompany", orderCompany);
	    	setAttr("orderCompanyName", orderCompanyName);
	    }

	    System.out.println("来电：  " + telCallNumb);
	    System.out.println("本机号：  " + telSelfNumb);

	    render("order_add3.ftl");
	
	}
	
	public void editOrder(){
		setAttr("fromUrl", getPara("fromurl")+"?"+getPara("param").replaceAll("amp;", "&"));
		setAttr("order", Order.dao.findById(getParaToInt()));
		render("order_edit.ftl");
	}
	
	@Before(Tx.class)
	public void eidtOrderSave(){
		String url=getPara("urll");
		int id = getParaToInt("id");
		String kilometre = getPara("order.kilometre");
		String totalmoney = getPara("order.totalmoney");
		
		Order order = Order.dao.findById(id);
		Driver driver = Driver.dao.findById(order.getInt("b_user_id"));
		if(order != null){
			Tel tel = Tel.dao.findFirst("select * from tel_company where company=?", order.getStr("source"));
			if(tel != null){
				int commissiontype = tel.getInt("commissiontype");
				int proportion = tel.getInt("proportion");
				
				BigDecimal oldcharges = ( order.getBigDecimal("charges") == null ? new BigDecimal(0) : order.getBigDecimal("charges"));
				BigDecimal oldtotalmoney = (order.getBigDecimal("totalmoney") == null ? new BigDecimal(0) : order.getBigDecimal("totalmoney"));
				Float twoTotalMoney = Float.valueOf(totalmoney);
				Float firstTotalMoney = oldtotalmoney.floatValue();
				if(commissiontype == 1 || commissiontype == 2){
					Float kouMoney = 0f;
					if(commissiontype == 1){
						/*String sql = "SELECT * FROM b_user_point_rule";
						List<Record> ruleList = Db.query(sql);
						int curproportion = 20;
						int curPoint = driver.getInt("point");
						for(Record record :ruleList){
							int startPoint = record.getInt("start_point");
							int endPoint = record.getInt("end_point");
							if(curPoint >= startPoint 
									&& curPoint <= endPoint){
								curproportion = record.getInt("proportion");
								break;
							}
						}*/
						Integer curproportion = (order.getInt("cur_proportion") == null? 20:order.getInt("cur_proportion"));
						kouMoney = ( (twoTotalMoney - firstTotalMoney) * curproportion ) / 100;
					}else{
						kouMoney = ( (twoTotalMoney - firstTotalMoney) * proportion ) / 100;
					}
					Float addIncomeMoney = twoTotalMoney - firstTotalMoney - kouMoney;
					
					String remarks = "oldcharges="+oldcharges+",oldtotalmoney="+oldtotalmoney+",totalmoney="+totalmoney+",proportion="+proportion;
					
					BigDecimal oldBalance = (driver.getBigDecimal("balance") == null ? new BigDecimal(0):driver.getBigDecimal("balance"));
					BigDecimal newBalance = oldBalance.subtract(new BigDecimal(kouMoney));
					
					BigDecimal oldIncome = (driver.getBigDecimal("income") == null ? new BigDecimal(0):driver.getBigDecimal("income"));
					BigDecimal newIncome = oldIncome.add(new BigDecimal(addIncomeMoney));
					
					String sqlInsert = "insert into b_user_balance_change(b_user_id,license_num,daymoney,before_balance, before_income, cur_balance,cur_income,commissiontype,remarks,payment_time,order_id) values (?,?,?,?,?,?,?,?,?,NOW(),?)";
					Db.update(sqlInsert, driver.getInt("id"), driver.getStr("license_num"),
							  			 kouMoney,oldBalance, oldIncome, newBalance, newIncome,
							  			 2,remarks,id);
					
					String sqlUpdateUser = "UPDATE b_user t set t.status = 0,t.income = ?,balance=? where id=?";
					Db.update(sqlUpdateUser, newIncome, newBalance, order.getInt("b_user_id"));
					
					//BigDecimal newCharge = oldcharges.add(new BigDecimal(kouMoney));
					BigDecimal newCharge = new BigDecimal(twoTotalMoney * proportion /100);
					Db.update("update order_detail set charges=? where id=?",newCharge,id);
				}else{
					Float kouMoney = twoTotalMoney - firstTotalMoney;
					BigDecimal newIncome = (driver.getBigDecimal("income") == null ? new BigDecimal(0):driver.getBigDecimal("income"));
					newIncome = newIncome.add(new BigDecimal(kouMoney));
					
					String sqlUpdateUser = "UPDATE b_user t set income=? where id=?";
					Db.update(sqlUpdateUser, newIncome, order.getInt("b_user_id"));
				}
			}
		}


        Date date=new Date();

        DateFormat dayTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String updatetime=dayTimeFormat.format(date);

		Db.update("update order_detail set kilometre=?,totalmoney=?,updatetime=? where id=?",kilometre,totalmoney,updatetime,id);
		
		if(StringUtils.isNotEmpty(url)){
			redirect(url, true);
			return;
		}
		redirect("/order/finishList");
	}
	
	public void addressupdate(){
		int orderId = getParaToInt();
		Order order = Order.dao.findById(orderId);
		setAttr("order", order);
		
		render("order_change_address.ftl");
	}
	
	public void saveUpdateAddress(){
		Order order = (Order)getModel(Order.class);
		String startpoint = getPara("startpoint");
		String endpoint = getPara("endpoint");
		
		Db.update("update order_detail set startpoint=?,endpoint=?," +
				  "startpoint_longitude=?,startpoint_latitude=?,endpoint_longitude=?,endpoint_latitude=? where id=?"
				  ,order.getStr("startpoint"),order.getStr("endpoint"),order.getBigDecimal("startpoint_longitude"),order.getBigDecimal("startpoint_latitude")
				  ,order.getBigDecimal("endpoint_longitude"),order.getBigDecimal("endpoint_latitude")
				  ,order.getInt("id"));
		
		Long orderState = order.getLong("order_state");
		if(orderState == 6){
			redirect("/order/assignmentList");
		}
		if(orderState == 0){
			redirect("/order/acceptList");
		}
		if(orderState == 1){
			redirect("/order/acceptedList");
		}
		if(orderState == 2){
			redirect("/order/arrivedList");
		}
	}
	
	public void toFinishOrder(){
		int orderId = getParaToInt();
		setAttr("orderId", orderId);
		
		render("to_finish_order.ftl");
	}
	
	//后台去结算
	@ClearInterceptor(ClearLayer.ALL)
	@Before({Tx.class, ExceptionInterceptor.class , SessionInViewInterceptor.class})
	public void orderCharge(){
		String charge = getPara("charge");
		String kilometre = getPara("kilometre");
		
		int orderId = getParaToInt();
		try{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date currDate = Calendar.getInstance().getTime();
			String resultTime = sdf.format(currDate).toString();
			
			
			Float totalmoney = Float.valueOf(charge);
			Order order = Order.dao.findById(orderId);
			
			Long orderState = order.getLong("order_state");
			int driverId = order.getInt("b_user_id");
			if(orderState == 3){
				Float newIncome = null, newBalance = null;
				int curproportion = 20;
				Float kcmoney = 0f;
				
				String company = order.getStr("source");
				String companySql = "select * from tel_company where company=?";
				Tel tel = Tel.dao.findFirst(companySql, company);
				if(tel == null){
					throw new RuntimeException("此订单没有订单来源，结算失败");
				}
				
				Driver driver = Driver.dao.findById(driverId);
				Integer curPoint = (driver.get("point") == null ? 0:driver.getInt("point"));
				Float oldBalance = (driver.getBigDecimal("balance") == null ? 0f: driver.getBigDecimal("balance").floatValue());
				Float oldIncome = (driver.getBigDecimal("income") == null ? 0f: driver.getBigDecimal("income").floatValue());
				String job_number = driver.getStr("job_number");
				String levelName = "列兵";
				
				String companyTel = tel.getStr("tel");
				Integer commissiontype = tel.getInt("commissiontype");
				int proportion = tel.getInt("proportion");
				String sunCompany = tel.getStr("sun_company");
				
				
				String sql = "SELECT * FROM b_user_point_rule";
				List<DriverPointRule> driverPointRuleList = DriverPointRule.dao.find(sql);
				for(DriverPointRule driverPointRule : driverPointRuleList){
					int startPoint = driverPointRule.getInt("start_point");
					int endPoint = driverPointRule.getInt("end_point");
					if(curPoint >= startPoint 
							&& curPoint <= endPoint){
						curproportion = driverPointRule.getInt("proportion");
						levelName = driverPointRule.getStr("level_name");
						break;
					}
				}
				
				if(1 == commissiontype){
					Float corpIncome = (totalmoney * curproportion) / 100;
					
					String lowerthanmoney = tel.getStr("lowerthanmoney");
					if(lowerthanmoney == null || "".equals(lowerthanmoney)){
						lowerthanmoney = "0";
					}
					String commissionmoney = (tel.getStr("commissionmoney") == null ? "0":tel.getStr("commissionmoney"));
					
					BigDecimal nowMoney = new BigDecimal(totalmoney);
					BigDecimal nowLowerthanmoney = new BigDecimal(lowerthanmoney);
					if(nowMoney.compareTo(nowLowerthanmoney) < 0){
						corpIncome = Float.parseFloat(commissionmoney);
					}
					
					newBalance = (float) (oldBalance - corpIncome);
					newIncome = (float) (oldIncome + (totalmoney - corpIncome));
					newBalance = (float) (Math.round(newBalance * 10)) / 10;
					newIncome = (float) (Math.round(newIncome * 10)) / 10;
					
					kcmoney = corpIncome;
				}
				//固定比例提成
				else if(2 == commissiontype){
					Float corpIncome = (totalmoney * proportion) / 100;
					
					String lowerthanmoney = tel.getStr("lowerthanmoney");
					if(lowerthanmoney == null || "".equals(lowerthanmoney)){
						lowerthanmoney = "0";
					}
					String commissionmoney = (tel.getStr("commissionmoney") == null ? "0":tel.getStr("commissionmoney"));
					if("".equals(commissionmoney)){
						commissionmoney = "0";
					}
					
					BigDecimal nowMoney = new BigDecimal(totalmoney);
					BigDecimal nowLowerthanmoney = new BigDecimal(lowerthanmoney);
					if(nowMoney.compareTo(nowLowerthanmoney) < 0){
						corpIncome = Float.parseFloat(commissionmoney);
					}
					
					newBalance = (float) (oldBalance - corpIncome);
					newIncome = (float) (oldIncome + (totalmoney - corpIncome));
					newBalance = (float) (Math.round(newBalance * 10)) / 10;
					newIncome = (float) (Math.round(newIncome * 10)) / 10;
					
					kcmoney = corpIncome;
				}
				//定时扣款
				else if(3 == commissiontype){
					kcmoney = 0f;
					newBalance = (float) (oldBalance - 0);
					newIncome = (float) (oldIncome + (totalmoney - 0));
					newBalance = (float) (Math.round(newBalance * 10)) / 10;
					newIncome = (float) (Math.round(newIncome * 10)) / 10;
				}
				log.info("UpdateOrderState new data: balance:"+newBalance+",income:"+newIncome+"proportion:"+proportion+",commissiontype:"+commissiontype);

				String sqlUpdate = " UPDATE order_detail SET order_state= ?, driver_finish_time = ?, totalmoney=?, commissiontype=?,kilometre=?,charges=?,remark=?,cur_proportion=? where id=?";
				
				String sqlUpdateUser = "UPDATE b_user t set status = 0,t.income = ?,balance=?,proportion=? where id=?";
				
				String inserSql3 = "insert into b_user_balance_change(b_user_id,license_num,daymoney,before_balance, before_income, cur_balance,cur_income,commissiontype,payment_time,order_id) values (?,?,?,?,?,?,?,?,NOW(),?)";
				
				String pointSql = "insert into b_user_point_log(point,user_id,order_id,create_time,remarks) values(?,?,?,now(),?)";
				
				String pointUpdateSql = "update b_user set point=ifnull(point,0)+? where id=?";
				
				//记录用户积分变化日志
				int point = 2;
				String remarks1 = "后台完成订单";
				if(new BigDecimal(3).compareTo(new BigDecimal(kilometre)) <= 0){
					point = 4;
					remarks1 = "后台完成订单+3公里";
				}
				Timestamp tt=new Timestamp(Calendar.getInstance().getTimeInMillis());
				Db.update(pointSql,point, driverId, orderId, remarks1);
				Db.update(pointUpdateSql, point, driverId);
				Db.update(inserSql3, driverId, company, kcmoney,oldBalance, oldIncome, newBalance, newIncome, commissiontype, orderId);
				Db.update(sqlUpdateUser, newIncome, newBalance, proportion, driverId);
				Db.update(sqlUpdate, 4, resultTime, totalmoney, commissiontype, kilometre, kcmoney, "后台人工结算", curproportion, orderId);
				
				String content = "";
				/*if("".equals(companyTel)){						
					content = "首长您好！工号："+job_number+"（"+levelName+"）为您提供的服务已经完成，费用总计："+totalmoney+"元，APP下单更方便（下载地址www.zglbapp.com），全国数万退伍军人为您保驾护航！("+sunCompany+")";
				}else{
					content = "首长您好！工号："+job_number+"（"+levelName+"）为您提供的服务已经完成，费用总计："+totalmoney+"元，APP下单更方便（下载地址www.zglbapp.com），全国数万退伍军人为您保驾护航，咨询电话："+companyTel+"！("+sunCompany+")";
				}*/
				String clientPhone=tel.getStr("client_phone");
				content="首长您好！本次由士兵："+job_number+"为您提供服务，总计："+totalmoney+"元，全国数万退伍军人为您保驾护航，服务热线"+clientPhone;
				
				Integer memberId = order.getInt("member_id");
				if(memberId == null || 0 == memberId){
					String memberPhone = order.getStr("cell_phone");
					SmsUtil.sendMessage(memberPhone,content,company);
					
					//String insertMessage = "insert into tel_company_message(TEL,MESSAGE,COMPANY,CREATE_TIME) values(?,?,?,?)";
					//Db.update(insertMessage,tel,content,company,new java.sql.Date(Calendar.getInstance().getTime().getTime()));
				}else{
					Member member = Member.dao.findById(memberId);
					if(member == null){
						throw new RuntimeException("此订单下单用户不存在，结算失败");
					}
					String phoneType = member.getStr("phone_type");
					String registerId = member.getStr("device_id");
					String memberPhone = member.getStr("user_name");
					if("IOS".equals(phoneType)){
						SmsUtil.sendPush(content, null, registerId, phoneType);
					}else if("ANDROID".equals(phoneType)){
						SmsUtil.sendPush("成功接单", content, registerId, phoneType);
					}else{
						//String insertMessage = "insert into tel_company_message(TEL,MESSAGE,COMPANY,CREATE_TIME) values(?,?,?,?)";
						//Db.update(insertMessage,tel,content,company,new java.sql.Date(Calendar.getInstance().getTime().getTime()));
						
						SmsUtil.sendMessage(memberPhone,content,company);
					}
				}
				
			}else{
				throw new RuntimeException("订单状态错误");
			}
		}catch(Exception e){
			log.error("收费失败：" + e) ;
			throw new RuntimeException("收费失败，请重试" , e);
		}
		redirect("/order/finishList");
	}
	public void executingList() {

        render("executing_list.ftl");
    }

    public void orderDetailView(){
        int orderId = getParaToInt();
        Order order = Order.dao.findById(orderId);

        String driver_name=Db.queryStr("select name from b_user where id= ?",order.get("b_user_id"));


        setAttr("driver_name",driver_name);

        setAttr("order", order);

        render("orderDetailView.ftl");
    }
    
    public void deliveryMoney(){
        String cityId=getPara("cityId");
        double distance=Double.parseDouble(getPara("kilomate"));
        int weight=getParaToInt("weight");
        String sql = "select * from b_delivery_price where city_id=?";
        
        if(distance==0){
            setAttr("money", 0);
            renderJson();
            return;
        }
        
        DeliveryPrice deliveryPrice = DeliveryPrice.dao.findFirst(sql, cityId);
        if(deliveryPrice == null || deliveryPrice.getInt("initialPrice") == null){
            throw new RuntimeException("算费规则不存在");
        }
        Integer initialPrice = deliveryPrice.getInt("initialPrice");
        Integer initialKm = deliveryPrice.getInt("initialKm");
        Integer overKm = deliveryPrice.getInt("overKm");
        Integer overPlusPrice = deliveryPrice.getInt("overPlusPrice");
        Integer initialWeight = deliveryPrice.getInt("initialWeight");
        Integer overPlusWeightPrice = deliveryPrice.getInt("overPlusWeightPrice");
        float totalmoney = 0f;
        if(initialKm.floatValue() >= distance){                 
            totalmoney = initialPrice.floatValue();
        }else{
            int weightCount=new Double(Math.ceil((distance - initialKm.floatValue()) / overKm)).intValue();
            totalmoney = initialPrice.floatValue() + weightCount * overPlusPrice;
        }
        Integer totalWeight = 0;
        if(weight == 0){
            totalWeight = initialWeight;
        }else{
            totalWeight =weight;
        }
        if(totalWeight > initialWeight){
            totalmoney = totalmoney + (totalWeight - initialWeight) * overPlusWeightPrice;
        }
        setAttr("money", totalmoney);
        renderJson();
        
    }
}

	
